Using Sphinx for generating course content

(Written by Martin Vogelaar, Kapteyn Astronomical Institute, Groningen, The Netherlands)

Introduction

In June 2013 we started an experiment with a document generator to structure and enhance our existing course material. The candidate course is a programming course and the programming language that we use is Python. Therefore our attention was immediately drawn to Sphinx. Sphinx (sphinx-doc.org/) is written by Georg Brandl and licensed under the BSD license. Other programming languages are also supported, but we wanted to test whether the tool is also usable for courses that are not related to a programming language but are rich with mathematical formulas. We concluded that Sphinx gives also added value to this category of courses.

Starting point

In the last decade, many teachers and lectures migrated their written course material to the Web. Advantages are the availability of the material and the relative low burden of maintenance. Also the use of HTML is straightforward and formulas could be included as images so material for science and engineering was not restricted to text and could be written and published by teachers themselves. But in the meantime, many new techniques were introduced to enhance these web courses, but they are often missed or not applied because of the extra work involved.

Our Python programming course was an ideal starting point. The course material was entirely in HTML. Spelling mistakes could be corrected very easily and other small changes could be applied immediately, all improving the documents while they were in use. Formulas were build with MimeTex. For writers who are familiar with LaTeX, this seemed a natural way to build formulas for the Web. But, compared to state of the art documentation on the Web, we saw many options for improvement. The most important were:

  1. The structure of the documents and the relation between documents was not optimal.
  2. The quality of the formulas was not very good and scaling them does worsen the quality.
  3. The formulas could not be numbered and not be referenced.
  4. A search facility was not available.
  5. We did not have an index file.
  6. There was not a straightforward way to display highlighted program code.
  7. There was no way to keep a plot and the code that generates it, together.
  8. Creating a PDF version was cumbersome.

HOWTO

(Written by Martina Tsvetanova, ASTRON, now at University of Twente, The Netherlands)

Our howto is written for the maintainers of a programming course at the Kapteyn Institute for which we use Sphinx to generate course content. To facilitate the course makers/maintainers, the following questions point to the locations of the corresponding answers in the text.

Frequent errors

There are several frequently repeating errors, which can become slightly hard to discover sometimes. Please check these in PART IV: Frequent errors.

Reading carefully the error messages would help to discover the error easier.

Part I

1. Introduction

Sphinx is powerful documentation generator. It creates Web pages, requiring almost no effort from the user. The generator is very convenient for programmers who have to display a lot of source code, automatically generated plots, or who need a good referencing system for their Python modules, objects and equations.

On the other hand, Sphinx can be used for ordinary web pages and is really user-friendly, all input from the user is plain text, without too many syntax rules.

This document aims to help the user to start a documentation project with Sphinx and explain basic rules for using the generator, as well as to give advise on particular procedures while designing the desired documentation. For more extended help and tutorials, please visit the following link http://sphinxsearch.com/docs/current.html.

2. Information before documentation creation

Before starting, the user should decide what is going to be the directory for the documentation. A lot of files will be constantly generated when updating the documentation, that is why the client has to choose a place with enough free space. He or she has to also decide what the name, author and release of the documentation should be. These titles will appear in several places of the web page so it is nice to prepare them initially.

3. Creating a documentation

To install Sphinx, use the instructions http://sphinx-doc.org/latest/install.html. It is required to at least have Python 2.6.

After installation the user can start with the documentation with:

$ sphinx-quickstart

The documentation will start to generate itself. Several questions will be asked. The user has to decide and answer.

Example can be seen below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
Welcome to the Sphinx 1.1.3 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]: tutorialdoc

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/N) [n]: y

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom style sheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
> Project name: tutorial documentation
> Author name(s): user

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
> Project version: 1.0
> Project release [1.0]: 2013

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
 > Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another file name
> Name of your master document (without suffix) [index]:

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/N) [n]: y

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/N) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/N) [n]: y
> intersphinx: link between Sphinx documentation of different projects (y/N) [n]: y
> todo: write "todo" entries that can be shown or hidden on build (y/N) [n]: y
> coverage: checks for documentation coverage (y/N) [n]: y
> pngmath: include math, rendered as PNG images (y/N) [n]: n
> mathjax: include math, rendered in the browser by MathJax (y/N) [n]: y
> ifconfig: conditional inclusion of content based on config values (y/N) [n]: y
> viewcode: include links to the source code of documented Python objects (y/N) [n]: y

Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (Y/n) [y]: y
> Create Windows command file? (Y/n) [y]: y

Creating file tutorialdoc/source/conf.py.
Creating file tutorialdoc/source/index.rst.
Creating file tutorialdoc/Makefile.
Creating file tutorialdoc/make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file tutorialdoc/source/index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. HTML, LaTeX or linkcheck.

Warning

pngmath and MathJax cannot be used at the same time for displaying mathematics. While pngmath displays an equation as an image, MathJax is using scalable vector graphics (quality remains the same after zooming).

Also, separation of the build and source folders is recommended, it allows` better insight in the documentation structure. Most of the other functionallities are always nice-to haves, so answering with yes is never a mistake.

The user needs to be sure what is expected from the Python documentation before building. Otherwise undesirable work might be needed later to fix the configuration file generated (conf.py).

4. Exploring newly created documentation and building

After creating the Sphinx documentation, it is recommended for the user to get acquainted with it. One should visit the directory where it is hosted. At first there are 2 other directories inside- source and build (if separated in the creation process) and 2 files- Makefile and make.bat. These are the files that should be never deleted, otherwise the documentation created would not be able to generate the HTML files for the Web pages This is also the working directory where the user has to type the command for building the HTML files:

$ sphinx-build -b html sourcedir builddir

Or only the following:

$ make html

Of course, before creating any output, there should be some input. The source directory should be visited first. Initially the build one is empty. When opened, it contains the master file- index.rst (or other name and txt extension if specified during the generation). Other present file is the conf.py file, which is responsible for a lot of documentation configurations. It is very well commented and easy to understand.

There are also the _static and _templates ddirectories which are empty if the user does not fill them in. These contain style-related files.

The start page of a documentation project will be generated from the master file (as named by the user in the documentation creation session).

In the same directory as the master file (index.rst if not specified otherwise), the user can create the other documentation files. Every file would correspond to a HTML page being generated after building. To refer to other file (page) in a file`s table of contents the toctree directive is used. If files are created in another directory, the path to them should be also added as in the example below.:

1
2
3
4
5
6
.. toctree::
   :maxdepth: 2

   document1.rst or /path/to/from/current/directory/document2.rst
   document3.rst
   ...

After building, the build directory will be written, containing doctrees directory and HTML directory. The HTML directory is the one containing the HTML output. With then toctree as above a hypothetical page will have links generated for the other pages- document1, document#, document2, etc.

While building the documentation, explore how the build and HTML directories change. While there is direct control on the source one, the build directory contains the HTML output so that is why it is important to observe the content. Also, changes will not become visible if the working rst (txt) file is not saved. Normally a message is displayed if the files in the source directory are up to date and about which files are exactly build. While building, messages show which files are being processed. It is important to observe the process in order to avoid surprises.

With Sphinx, also LaTeX and PDF output can be generated. The command for generating LaTeX output is make latex and for generating PDF of the documentation- make latexpdf. Similar to the HTML output a LaTeX output directory will appear in the build directory, containing the generated files.

Building a PDF is not trivial. The process is sensitive to particular problems with the interpretation of LaTeX as it seems. For example, the usage of eqnarray in the output causes errors. They can be still solved by using LaTeX line breaks (\\) and still write the equations on the same line. The building process puts the result in /source/LaTeX but then it is not yet available as a link to your HTML documentation, so you should run ‘make html’ again. Please ignore LaTeX warnings by pressing ‘Enter’ while building PDF to at least force some usable output. Also check at the end if the PDF was generated. With severe errors, the building process does not create a newer version. The PDF would include documents in the toctree. If the user wants to refer to a rst document without putting it in the tocree and generating PDF of it, he/she could use the doc role.

As already visible in the creation phase, TeXinfo and Epub output can be also generated.

For resume of the various builders and output possibilities, the reader can visit the following page with available builders http://sphinx-doc.org/builders.html.

5. Basic syntax

Headings and comments

All content to a sphinx page can be added with plain text. There is no hard syntax to learn.

The sections in a file as the one below are considered comments:

.. text

When a title of a subsection has to be created, the line needs to be underlined with #, =, *, -, ^ or ". There are no heading levels assigned but it is important to keep consistency because the structure is determined from the succession of headings. It is good to experiment at first to find the most comfortable for the user way. Of course, the usr is free to use other characters but it is important to realize that there is limitation how deep the nesting of sections can be (limited for LaTeX)

The underlining can be longer than the title, but not shorter:

1
2
3
4
5
6
7
8
9
Title  -valid header
======

Title  -invalid header
===

==========================
This is also valid heading
==========================

Every title is being added as node in the table of contents of the page, adding up to the nodes created by the toctree. If the user does not want that, he or she should use:

.. rubric:: title

Paragraphs and text boxes

Paragraphs start on a new line, separated from previous and next sections with a blank line.

Sphinx works with directives and options. Several directives can be used specifically in order to improve the text arrangement.

For a coloured box with some title the user can apply the topic directive:

.. topic:: title

   Text

It is very important to keep the indentation and the blank line, also a blank line at the end of every logical block in the plain text.

For a warning box the syntax is as follows:

.. Warning::

   Text

For ‘seealso’ box and note box, the idea is the same:

1
2
3
4
5
6
7
.. seealso::

   Text

.. note::

   Text

The results would be respectively:

title

Text

Warning

Text

See also

Text

Note

Text

A lot more options are available.

Todo boxes are also possible:

.. todo::

   Text

Resulting in:

Todo

Text

Before being able to use the directive, the user needs to add the following extension: sphinx.ext.todo (if not present in the array with extensions at conf.py and also set the variable todo_include_todos to True. If there is no line for this in conf.py, then one should be added:

todo_include_todos= True

Warning

The style hereby is custom. All blocks could be given different background and general appearance throughout style sheet changes.

Literal text can be displayed with literal text markup text within a line or a whole paragraph- with ”::” at the end of the previous paragraph:

Previous paparagraph. text... text::

  Literal paragraph... indentation should be used.

Markup within a paragraph such as *text* or **text** stands respectively for italics and emphasis. Inline literal blocks could be achieved by: ``text``.

Pictures and figures

To insert a picture, the user needs to add the following structure:

1
2
3
4
5
.. image:: ../images/image.png
   :width: ??px
   :align: center
   :height: ??px
   :alt: caption

To import the image as figure the syntax is rather the same:

1
2
3
4
5
6
7
.. figure:: ../images/image.png
   :width: ??px
   :align: center
   :height: ??px
   :alt: caption

   Could add text here

It has to be notified that the specified path is relative to the source directory. This means that if directly the title of the image is given, it is in the same directory as the rst files.

Lists and tables

Creating lists is very easy job. The simplest list is basically a list of bullet points:

  • item1
  • item2
  • item3
  • item1
  • item2
  • item3

Numbered lists just include numbering:

1. item1
2. item2
3. item3
  1. item1
  2. item2
  3. item3

Autonumbering is also possible:

#. autonumber item
  1. autonumber item

In order to make the list looking more clean, the user can apply the following:

1
2
3
4
5
6
7
8
.. hlist::
   :columns: 3

   * A list of
   * short items
   * that should be
   * displayed
   * horizontally
  • A list of
  • short items
  • that should be
  • displayed
  • horizontally

Warning

Depending on the version of the builder that is present on the client machine, the effect can vary.

Tables are also very simplke to create. All the user needs is to “draw it”.

Example:

1
2
3
4
5
6
7
8
+------------------------+------------+----------+----------+
| Header    Title        | Title      | Title    | Title    |
|                        |            |          |          |
+========================+============+==========+==========+
| row1        column 1   | column 2   | column 3 | column 4 |
+------------------------+------------+----------+----------+
| row 2                  | ...        | ...      |          |
+------------------------+------------+----------+----------+
Header Title Title Title Title
row1 column 1 column 2 column 3 column 4
row 2 ... ...  

The “=” underlining is optional. When added it emphasizes and colors the headers.

Other table options are also avavailable

A B C
.    
.    
.    
A B C
.    
.    
.    

A very simple table format is the csv-table. It does not require pre-drawing:

1
2
3
4
5
6
.. csv-table:: a title
   :header: "first header", "second header", "third header"
   :widths: 20, 20, 10

   "item 1", "item 2", 3
   "item 4", "item 5", 5
a title
first header second header third header
item 1 item 2 3
item 4 item 5 5

However, it has to be noted that with this format there is no control over the merging of cells.

Warning

The user should be careful with the spacing in the csv-table syntax. The comma needs to be exactly after the quotes and 1 space separated from the next quotes.

To control the text line break in a listing without using tables or lists, the user can apply the following topology:

| line 1
| line 2
line 1
line 2

A lot of other possibilities are available for stylish output. Separate extensions and style methods can also be written in order to reach the desired output.

6. Page content and documentation structure

Sphinx documentation has a simple structure. It consists of the files that were created and the connections between them are specified within the files toctrees (table of contents).

The paragraph titles from every document are included in the table of contents. Tables of contents from all sub documents are inserted also, with a maximum depth of maxdepth. One uses maxdepth to avoid too much detail in a table of contents:

1
2
3
4
5
6
.. toctree::
   :maxdepth: 2

   document1.rst
   document2.rst
   ...

A depth of 1 is displays only the sub documents the current page. A depth of 2 displays the document names and the titles of their subsections as well. Higher :maxdepth: is analogous. In order to remove a single section header from the table of contents, look at the answer of question 12.

7. Sphinx configuration file

The main Sphinx configuration file can be found in the source and also in the HTML output (after building) directories. Hereby we supply an example of a modified configuration file.

Warning

This file has been modified for our documentation project and will differ from yours!

You can download and inspect this configuration file: conf.py

Lets start with the initial section. It represents the general configuration:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
 # -*- coding: utf-8 -*-
 #
 # Introduction to Programming and Computational Methods build configuration file, created by
 # sphinx-quickstart on Tue Aug 27 11:53:19 2013.
 #
 # This file is execfile()d with the current directory set to its containing dir.
 #
 # Note that not all possible configuration values are present in this
 # autogenerated file.
 #
 # All configuration values have a default; values that are commented out
 # serve to show the default.

 import sys, os
 CURDIR = os.path.abspath(os.path.dirname(__file__))
 # If extensions (or modules to document with autodoc) are in another directory,
 # add these directories to sys.path 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.join(os.path.abspath(os.path.dirname(__file__)), 'sphinxext'))

 # -- General configuration -----------------------------------------------------

 # If your documentation needs a minimal Sphinx version, state it here.
 #needs_sphinx = '1.0'

 # -- plot directive script:
 #
 #plot_ext = 'matplotlib.sphinxext.plot_directive'  # 'official'
 plot_ext = 'plot_directive'                       # local

 plot_figwidth = '60%'  # Works with latest plot_directive adapted by Hans Terlouw 12-4-2014

 math_ext = 'sphinx.ext.mathjax'
 mathjax_path = '/MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML'

 # 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', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo',
           'sphinx.ext.coverage', math_ext, plot_ext, 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode',
           'figtable', 'question']

 todo_include_todos=True #To allow todo notes and lists

 # Add any paths that contain templates here, relative to this directory.
 templates_path = ['_templates']

 # The suffix of source filfile names
 source_suffix = '.rst'

 # The encoding of source files.
 #source_encoding = 'utf-8-sig'

 # The master toctree document.
 master_doc = 'index'

 # General information about the project.
 project = u'Introduction to Programming and Computational Methods'
 copyright = u'2014, Martin Vogelaar'

 # The version info for the project you're documenting, acts as replacement for
 # |version| and |release|, also used in various other places throughout the
 # built documents.
 #
 # The short X.Y version.
 version = '1.0'
 # The full version, including alpha/beta/rc tags.
 release = '2014'

 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
 #language = None

 # 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 patterns, relative to source directory, that match files and
 # directories to ignore when looking for source files.
 exclude_patterns = []

 # The reST default role (used for this markup: `text`) to use for all documents.
 #default_role = None

 # 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'

 # A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

The comments help a lot to understand the functionality of an option. This example is extracted from a file which was customized by us. If the user opens the original file, it becomes obvious what has been changed.

The lines:

import sys, os
CURDIR = os.path.abspath(os.path.dirname(__file__))

help specifying the directory that contains the conf.py file.

By the following:

sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'sphinxext'))

A user can specify a directory which includes the extensions location. In the current example, a directory called sphinxext was created in the source directory which was filled in with any custom extensions.

The user can add also other directories in the source directory which could be filled in with files for referencing. For example, the user could add a directory for text files, pictures and other. This is not going to change the documentation structure. These directoried could be also outside the source directory, but when referencing their pat, it should be known relative to the source location. The locations do not need to be added in the configuration file.

The lines:

1
2
3
4
5
6
# -- plot directive script:
#
#plot_ext = 'matplotlib.sphinxext.plot_directive'  # 'official'
plot_ext = 'plot_directive'                       # local

plot_figwidth = '60%'  # Works with latest plot_directive adapted by Hans Terlouw 12-4-2014

show that the user had created a custom extension plot_directive (positioned in the created sphinxext directory). That is why the official extension declaration is commented.

The last line indicates that this new extension is having options that can be configured in the current file. Later on in the page custom extension section the reader can find the code of this custom extension, illustrating the possibility Sphinx provides for customisation.

Continuing further, we see the specification of the path for MathJax (in case this is the math option sselected:

math_ext = 'sphinx.ext.mathjax'
mathjax_path = '/MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML'

The official extension is used and its location on the server is specified. In case that the reader uses Sphinx on a personal machine, then the path to where MathJax is located might be different of course. The path can be absolute or relative. If it is relative, it is relative to the _static directory of the built docs.

The next part of the general configuration continues with the extensions that are used in the documentation. A list of strings that are module names of Sphinx extensions. These can be extensions coming with Sphinx (named sphinx.ext.*) or custom ones:

extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest',
              'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage',
              math_ext, plot_ext, 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode',
              'figtable', 'question']

In the current example, the user can find several custom extensions next to the other ones, already provided by Sphinx. The remaining part of the general configuration is self explanatory. Some options and paths have been already specified in the documentation creation phase as well.

The next section in the configuration file is the HTML output section:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
#html_theme_options

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
html_title = "Introduction to Programming and Computational Methods"

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None
html_short_title = "Prognum"


# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = 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 = ['_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_domain_indices = True

# If false, no index is generated.
html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = 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 = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'IntroductiontoProgrammingandComputationalMethodsdoc'

The explanation in the comments is crucial for the understanding the functionality. Later on the usage of themes is shortly reviewed. Hereby the default HTML theme provided by Sphinx is used. The path to the style sheets specified to be html_static_path = ['_static'], which is the _static directory in the source of the documentation. Also, the HTML is provided with copyright for the example above. Index generation is allowed.

(depends if the user wants to expose the rst code or not), the page source could be hidden by html_show_sourcelink = False in conf.py as above.

After the HTML output section, the configuration file contains similar section for the LaTeX output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# -- Options for LaTeX output --------------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
  ('index', 'IntroductiontoProgrammingandComputationalMethods.tex',
   u'Introduction to Programming and Computational Methods',
   u'Martin Vogelaar', '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

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
latex_domain_indices = True

Hereby the reader can find the options for the paper size, appendices, font size, chapter numbering etc. The LaTeX documents section is specified already in the documentation creation section.

The conf.py file then contains the following sections, analogous to the LaTeX output section, dealing with the options for manual page, Texinfo and Epub output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
 # -- Options for manual page output --------------------------------------------

 # One entry per manual page. List of tuples
 # (source start file, name, description, authors, manual section).
 man_pages = [
     ('index', 'introductiontoprogrammingandcomputationalmethods',
      u'Introduction to Programming and Computational Methods',
      [u'Martin Vogelaar'], 1)
 ]

 # If true, show URL addresses after external links.
 #man_show_urls = False


 # -- Options for Texinfo output ------------------------------------------------

 # Grouping the document tree into Texinfo files. List of tuples
 # (source start file, target name, title, author,
 #  dir menu entry, description, category)
 texinfo_documents = [
   ('index', 'IntroductiontoProgrammingandComputationalMethods',
    u'Introduction to Programming and Computational Methods',
    u'Martin Vogelaar', 'IntroductiontoProgrammingandComputationalMethods',
    'One line description of project.',
    'Miscellaneous'),
 ]

 # Documents to append as an appendix to all manuals.
 #texinfo_appendices = []

 # If false, no module index is generated.
 #texinfo_domain_indices = True

 # How to display URL addresses: 'footnote', 'no', or 'inline'.
 #texinfo_show_urls = 'footnote'


 # -- Options for Epub output ---------------------------------------------------

 # Bibliographic Dublin Core info.
 epub_title = u'Introduction to Programming and Computational Methods'
 epub_author = u'Martin Vogelaar'
 epub_publisher = u'Martin Vogelaar'
 epub_copyright = u'2014, Martin Vogelaar'

 # The language of the text. It defaults to the language option
 # or en if the language is not set.
 #epub_language = ''

 # The scheme of the identifier. Typical schemes are ISBN or URL.
 #epub_scheme = ''

 # The unique identifier of the text. This can be a ISBN number
 # or the project homepage.
 #epub_identifier = ''

# A unique identification for the text.
 #epub_uid = ''

 # A tuple containing the cover image and cover page html template fifile names
 #epub_cover = ()

 # HTML files that should be inserted before the pages created by sphinx.
 # The format is a list of tuples containing the path and title.
 #epub_pre_files = []

 # HTML files shat should be inserted after the pages created by sphinx.
 # The format is a list of tuples containing the path and title.
 #epub_post_files = []

 # A list of files that should not be packed into the epub file.
 #epub_exclude_files = []

 # The depth of the table of contents in toc.ncx.
 #epub_tocdepth = 3

 # Allow duplicate toc entries.
 #epub_tocdup = True

At the end of this section the intersphinx mapping configuration is discussed. In order to be able to reference parts of other Sphinx documentations, the intersphinx extension (sphinx.ext.intersphinx) should be added in the extensions section. It can generate automatic linking to objects in other Sphinx documentation projects The user has to specify in the configuration file which are the documentation projects of interest:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# -- Intersphinx linking ---------------------------------------------------

intersphinx_cache_limit = 10     # days to keep the cached inventories
_python_doc_base = 'http://docs.python.org/2.7'
_numpy_doc_base = 'http://scikit-learn.org/stable'
intersphinx_mapping = {
     _python_doc_base: None,
     'http://docs.scipy.org/doc/numpy': None,
     'http://docs.scipy.org/doc/scipy/reference': None,
     _numpy_doc_base: None,
     'matplotlib':('http://matplotlib.sourceforge.net', None),
     'pyfits':('http://pythonhosted.org/pyfits/', None)
 }

The example above illustrates that there are 2 ways of specifying the link to the documentation- through direct citing or with a variable. Also, the last 2 lines give another alternative syntax which also uses identifier before the tuple. All of them are correct and can be applied.

The code above works simple. The target (the base URI of external documentation or local path) is mapped to its inventory (inventory file). The key word “None” indicates that the objects inventory file (obj.inv) can be found at the same location. If not, another URI should be supplied.

In order to be able to reference an object from other documentation, this object should be part of the inventory file.

The rst syntax for referencing is discussed later in the second part of the howto Intersphinx mapping.

8. Page basic style understanding

style sheets and configuration

There are 3 files responsible for the sphinx page appearance. These are the basic.css, default.css and pygments.css, positioned in the _static directory under build/html. This is in case the default HTML theme has been selected in conf.py - HTML output configuration.

Sphinx allows changing of the style of the HTML via themes. Theme option is present in the Sphinx configuration file conf.py. There are several options, explained on this page: http://sphinx-doc.org/theming.html.

An example of setting up the default theme is given below. In this example the sidebar is positioned at the right:

html_theme = "default"
html_theme_options = {
    "rightsidebar": "true"
}

The page http://sphinx-doc.org/theming.html also explains the options that can be altered in the conf.py file. However, altering the configuration file might not bring all the desired output. Especially for other themes (different than the default one), options might not be available. In such cases the user can alter the style sheets themselves. He/She needs to copy the style sheets from the _static directory under build/html to the _static directory under source. In that case, whatever is changed in the style sheets under the source location will be remembered after building the documentation

basic examples (default theme used)

In this section there are only basic examples.

In case options are not used in conf.py, to change the position of the sidebar and align it from left to the right, the default.css and the basic.css files need to be altered.

In basic.css:

1
2
3
4
5
6
div.sphinxsidebar {
    float: left--->right; -change from left to right
    width: 230px;
    margin-left: -100%;
    font-size: 90%;
}

In default.css

div.bodywrapper {
    margin: 0 0 0 230px---> 0 230px 0 0;
}

Under the default theme the sidebar location can be changed via conf.py as well. Look at the HTML theming support

For changing the background of the sidebar (the page background), the default.css file needs to be altered. The location in the file is:

div.document {
    background-color: #1c4e63;
}

To change the text background the location is:

1
2
3
4
5
div.body {
    background-color: #ffffff;
    color: #000000;
    padding: 0 20px 30px 20px;
}

Also look at the HTML theming support

custom style methods

In the style sheet, the user can define custom methods and later on use them in the rst files after defining a role with the method name.

For example, if a user would like to have a method for inline text color, then the following method can be created in one of the style sheets default.css or basic.css or other style sheets:

1
2
3
4
5
.red {

   color: red;

 }

Then the following should appear at the beginning of the rst file where the method should be used:

.. role:: red

From then on the user could use :red:`text` in order to have the text in red. When using the container directive, a whole paragraph can be given particular style:

.. container:: red

   Here the full block is red.
Here the full block is red.

Part II

1. Displaying mathematics and generating plots

Inline mathematics, equation arrays and referencing

The current page uses MathJax for displaying the mathematics.

The following procedure ilillustrateshe use of inline mathematics:

Text :math:`a^2+ b^2= c^2` text.

Text \(a^2+ b^2= c^2\) text.

To display single equation on a new row the following syntax is used:

.. math:: a^2+ b^2= c^2
   :label: some_label1

or:

.. math::
   :label: some_label2

   a^2+ b^2= c^2
(1)\[a^2+ b^2= c^2\]
(2)\[a^2+ b^2= c^2\]

In the example above some_label refers to the equation name and how the user can reference it. The reader needs to use `:eq:`some_label` to refer to the equation. Example: (1), (2).

The signs are traditional for the TeX format: “+” is used for plus, “-” for minus, “*” for multiplication, “frac{}{}” for division, “^” for powers, etc.

To display arrays of mathematical equations, the following option is very suitable, because later on the equations can be referenced under the same label:

1
2
3
4
5
6
7
8
.. math::
   :label: some_label3

   \begin{eqnarray}
     a^2+ b^2= c^2\\
     a^2+ b^2= c^2\\
     a^2+ b^2= c^2\\
   \end{eqnarray}

or:

.. math:: a^2+ b^2= c^2\\ a^2+ b^2= c^2\\ a^2+ b^2= c^2\\
   :label: some_label4
(3)\[\begin{split}\begin{eqnarray} a^2+ b^2= c^2\\ a^2+ b^2= c^2\\ a^2+ b^2= c^2 \end{eqnarray}\end{split}\]
(4)\[\begin{split}a^2+ b^2= c^2\\ a^2+ b^2= c^2\\ a^2+ b^2= c^2\end{split}\]

Display options: PNGmath and MathJax

There are 2 options to display mathematics in Sphinx generated document. One of them is using PNGmath- showing the equations as an image and the other is using MathJax. MathJax is a cross-browser JavaScript library that displays mathematical notation, using MathML, LaTeX and ASCIIMathML markup.

During installation the user has a option to choose between the 2 options. In the case MathJax is used it also needs to be installed. For speed and reliability we installed MathJax on a local server.

The installation is explained on (in case installation is performed on local machine): http://docs.mathjax.org/en/v1.1-latest/installation.html.

Following the suggested tests in the link is advisable. It is nice to have the MathJax directory within the documentation directory.

If the mathematics is still displayed as image, the user can check the conf.py file (within the source and build directory). The extensions section may still be ordered in a way that the MathJax extension is overwritten.

This is an example of the extensions section:

extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx',
             'sphinx.ext.todo', 'sphinx.ext.coverage',
             'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode']

Only one extension should be kept for the mathematics output.

The font size of the block mathematics can be altered from the default.css style sheet or other style sheet being used):

1
2
3
4
5
6
7
8
div.math {
       text-align: center;
       margin: 1em 0em;
       position: relative;
       display: block;
       width: 100%;
       font-size: 90%;
}

For the inline mathematics the procedure would include a more complicated approach and was not done within our PROGNUM documentation. The MathJax configuration file has to be altered.

Generating plots automatically

It is possible to generate plots automatically using Python code. The tool that makes this possible is the so called plot directive:

.. plot:: pyplots/code.py

From above, pyplots corresponds to the new directory the user needs to create within the source, and this new directory should contain the Python code code.py. As a result, the new “plot_directive” will be created within the build directory and also the plots will appear as images within the _images directory within build/html.

On the website this will result in a good quality output, available for downloading. The user can choose to display or hide the code which created the plot. In order to display it, the “include-source” option should be added:

.. plot:: pyplots/code.py
   :include-source:

In the examples below the plot is generated from external file and :include-source: is used for the first graph while for the second one not:

.. plot:: examples/circleMC.py
   :include-source: - not for second plot
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import numpy as np
from matplotlib.pyplot import figure, show
from matplotlib.patches import Arc
from matplotlib.cm import copper

fig = figure()
frame = fig.add_subplot(1,1,1)
n = 2000
x = np.random.random_sample(n)
y = np.random.random_sample(n)
radius = x**2 + y**2
In = (radius <= 1.0)
Out = (radius > 1.0)
frame.plot(x[In], y[In], 'g.')
frame.plot(x[Out], y[Out], 'r.')
arc = Arc((0,0), 2,2, 0,0, 90)
frame.add_patch(arc)
frame.imshow([[0, 0],[1,1]], interpolation='bicubic', cmap=copper,
             vmin=-0.5, vmax=0.5,
             extent=(frame.get_xlim()[0], frame.get_xlim()[1],
                     frame.get_ylim()[0], frame.get_ylim()[1]),
             alpha=1)

frame.set_xlim(0,1)
frame.set_ylim(0,1)
frame.set_aspect(1.0)
show()

(Source code, png, hires.png, pdf)

_images/circleMC.png

(Source code, png, hires.png, pdf)

_images/circleMC.png

Warning

Before being able to use the standard plot_directive, the user needs to include the following extension in conf.py extensions: extensions = ['matplotlib.sphinxext.plot_directive' ...]. The extension itself is written for Matplotlib and the code is available at: https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/sphinxext/plot_directive.py

A plot_directive directory will appear in the build directory, including the images and PDF’s produced for the plotting and showing of the source code.

Later in the howto there is an explanation on customizing the plot_directive extension Customizing the plot_directive.

3. Code blocks

To create a Python code-block the user can type simply type:

.. code-block:: python

   code here

In order to number the lines, the user can type the :linenos: option. For example, consider the code-block below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.. code-block:: python
   :linenos:

   from __future__ import division
   import numpy

   def volume(height, radius):
      pi = 3.14
      vol = (1.0/3.0) * height * pi * pow(radius,2)
      return vol

   vol = volume(2.0, 10)
   print vol, "(m^3)"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from __future__ import division
import numpy

def volume(height, radius):
   pi = 3.14
   vol = (1.0/3.0) * height * pi * pow(radius,2)
   return vol

vol = volume(2.0, 10)
print vol, "(m^3)"

Long literal blocks (code or other, in LaTeX verbatim) could be also included via a file, so they do not need to be written in the rst code. Then the user can apply the literalinclude directive:

.. literalinclude:: file_including_code

Example: - Examine the complex plane with phase plots

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import numpy
from matplotlib.pyplot import figure, show

xlo = -2; xhi = 2
ylo = xlo; yhi = xhi
x = numpy.linspace(xlo,xhi,100)
y = numpy.linspace(ylo,yhi,100)
xx,yy = numpy.meshgrid(x,y)
z = xx + yy*1j
zi = (z**2-1j)/(2*z**2+2j)
zi = numpy.angle(zi)

fig = figure()
frame = fig.add_subplot(1,1,1)
frame.imshow(zi, origin='lower', extent=[xlo,xhi, ylo,yhi])
show()

The code that the reader sees has been numbered without adding an option for that in the directive. Automatic numbering of the code blocks (the literal blocks starting with :: are also code blocks) can be initiated by the highlights directive:

.. highlight:: python
   :linenothreshold: 5

The code above positioned at the beginning of the rst file would number all Python code blocks with lines more than 5.

Warning

The Pygments style sheet is responsible for this. It needs to be present. The example for the complex numbers was numbered exactly because in the current page the highlight directive is used.

The highlight directive could be set for other languages such as C for example. Every highlight is active until the next usage of the directive. Additionally, the individual code-blocks could be used with the guess option in order to detect the right language.

More on the usage of highlights and code-blocks can be found at:

http://sphinx-doc.org/markup/code.html

4. Usage of customized extensions

As it was mentioned already, custom extensions can be written in order to supply new desired functionality when the provided Sphinx extensions are not able to provide it. In this section there are 2 examples of custom extensions. The custom extensions should be mentioned in the configuration file and also supplied in an extension directory whose path is also given in conf.py. Check again the General configuration section

Custom plot_directive

Sphinx provides extensions for including Matplotlib plots in a Sphinx document. The plot is generated from Python code while building the documentation. This directive can be altered in a way to provide numerous options for the user for better control.

The code below represents a plot directive extension, adapted by Hans Terlouw. While the original plot_directive has limited control (caused by a bug) the modified extension makes it possible to control the size and centering of the plots. Additionally, line numbers are supplied for the Python code (in case the user decides to show it). The modifications are very well explained at the beginning of the “MODIFIED” section.

Custom_plot_directive

Below there are 2 examples, shown again with the same code as when explaining the standard plot directive. Here the user can discover that the customized directive gives better control:

.. plot:: examples/circleMC.py
  :align: center
  :height: 300
  :include-source:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import numpy as np
from matplotlib.pyplot import figure, show
from matplotlib.patches import Arc
from matplotlib.cm import copper

fig = figure()
frame = fig.add_subplot(1,1,1)
n = 2000
x = np.random.random_sample(n)
y = np.random.random_sample(n)
radius = x**2 + y**2
In = (radius <= 1.0)
Out = (radius > 1.0)
frame.plot(x[In], y[In], 'g.')
frame.plot(x[Out], y[Out], 'r.')
arc = Arc((0,0), 2,2, 0,0, 90)
frame.add_patch(arc)
frame.imshow([[0, 0],[1,1]], interpolation='bicubic', cmap=copper,
             vmin=-0.5, vmax=0.5,
             extent=(frame.get_xlim()[0], frame.get_xlim()[1],
                     frame.get_ylim()[0], frame.get_ylim()[1]),
             alpha=1)

frame.set_xlim(0,1)
frame.set_ylim(0,1)
frame.set_aspect(1.0)
show()

(Source code, png, hires.png, pdf)

_images/circleMC.png

-Ratio of area of a circle and square with a Monte Carlo simulation-

.. plot:: examples/circleMC.py
   :align: center
   :height: 300
   :hide-source:

(png, hires.png, pdf)

_images/circleMC.png

-Ratio of area of a circle and square with a Monte Carlo simulation-

The user can see that with the customization of the directive, the link to the source of the plot is suppressed if you use :hide-source. Also, centering, height and width are working in combination with each other also.

Custom Question extension

This example extension is used in a Sphinx generated Python course. The role of it is to consequently number the questions in the course by putting the question under the directive:

Question 1

Question 2

In every new chapter of the course, the counting could be restarted via the simple option:

.. question::
   :number: 1

Question 1

The extension was created by Hans Terlouw and is available at:

Custom_question_extension

PART III: PROGNUM examples and problems solved

In this section the reader can find examples from the Python programming course which was registered under the name PROGNUM.

1. Raw HTML

One of the first encountered problems was how to migrate very big pieces of HTML code form old documentation- such as a big table or another piece of documentation in HTML that would require a lot of effort.

The directive raw can be used then. The syntax is the following:

.. raw:: html

   html code

Unfortunately, the HTML output would become only visible for the web page version of the documentation and not in the generated PDF. That is why the usage of raw was restricted only for linking. Links in Sphinx open in the same page. This is not al,ways what you want/ With raw HTML it was possible to open pages in another tab. For this the link needs to be defined before usage. Lets look at the following example:

1
2
3
4
5
6
.. |timetable| raw:: html

   <a href='http://www.rug.nl/fwn/roosters/2013/vakken/stpce5' target='_blank'>FWN Roster</a>


|timetable|

This would result in a link to a Web page with a roster that opens in a new tab: FWN Roster

2. Question container

The following output could be produced really easy. It was important to create blocks visible enough to get the attention of the student who wants an overview of the questions in a task. Note that we used option number to set the question number!

Question 5

_images/question01.png
The text of the question.

It could also be indented:

Question 5

_images/question01.png
The text of the question.

There are several tasks to perform before being able to produce the same output:

  1. Download the Custom_question_extension
  2. Add the extension to the custom extensions folder (most likely you called it sphinxext).
  3. Choose a proper image, such as question01.png and add it to a directory with the pictures you use. In the example above this is a directory called pictures under the source directory.
  4. Create the following style methods in default.css or basic.css. They are responsible for the appearance:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
.questiontext{
   display: table-cell;
   vertical-align: top;
   color: blue;
   padding: 1px;
   width:85%;
 }
 .questionimage{
   display: table-cell;
   padding: 10px;
   width: 30px;
   vertical-align: top;
 }

As the reader can find out, the output is a combination of css and Sphinx output. In order to use the roles in the style sheet called questionimage and questiontext, we apply the container directive. The indentation in the example comes from the fact that we are nesting blocks. The option :number: at the beginning is to indicate the initial number from which the counting starts. To prove this, the next example should have number 6:

1
2
3
4
5
6
7
8
9
.. question::

   .. container:: questionimage

      .. image:: pictures/question01.png

   .. container:: questiontext

      The text of the question.

Question 6

_images/question01.png
The text of the question.

3. Plotting

Below, the reader can find several examples of the usage of the plot directive in the PROGNUM course. It is important to note that PROGNUM uses the new custom plot directive (Custom_plot_directive). Also, all required code should be available in the examples directory:

1
2
3
4
5
.. plot:: examples/hubbleplot.py
   :align: center
   :height: 300px

   *- Hubble relation data -*

(Source code, png, hires.png, pdf)

_images/hubbleplot.png

- Hubble relation data -

1
2
3
4
5
6
7
8
.. plot:: examples/rotmatrix_ecliptic.py
   :height: 300px
   :align: center

   *- The blue plane is the equatorial system. The green plane is the
   ecliptic plane after rotation with the transpose of  E = E_x(23.43). Note that
   the x axis of the ecliptic also points to the vernal equinox. Note also the
   difference in orientation with the previous plot.*

(Source code, png, hires.png, pdf)

_images/rotmatrix_ecliptic.png

- The blue plane is the equatorial system. The green plane is the ecliptic plane after rotation with the transpose of E = E_x(23.43). Note that the x axis of the ecliptic also points to the vernal equinox. Note also the difference in orientation with the previous plot.

1
2
3
4
5
6
7
8
.. plot:: examples/rotmatrix_galsys.py
   :height: 300px
   :align: center

   *- The blue plane is the equatorial system. The green plane is
   the galactic plane after rotation with the transpose of
   E = E_z(180-123).E_y(90-27.4).E_z(192.25). The galactic pole is
   at (R.A., Dec) = (192.25, 27.4).*

(Source code, png, hires.png, pdf)

_images/rotmatrix_galsys.png

- The blue plane is the equatorial system. The green plane is the galactic plane after rotation with the transpose of E = E_z(180-123).E_y(90-27.4).E_z(192.25). The galactic pole is at (R.A., Dec) = (192.25, 27.4).

4. Tables

When using tables in Sphinx, it is still possible to have inline markup and linking, as in the following PROGNUM example: Please find the code for the table in the csv_table.txt file.

- NumPy functions related to complex numbers -
Function Description Example
numpy.array() Create array with complex numbers. Use dtype ‘F’, ‘G’ or ‘D’ z = numpy.array([3,2,1,0], dtype='complex64'), z = numpy.array([3,2,1,0], dtype='F')
numpy.ndarray.astype() Convert float array to complex z = x.astype('F'), z = x*1j
numpy.complex() Create a complex number from a real part and an optional imaginary part z = numpy.complex(3.2)
numpy.real(), numpy.imag() Create new arrays with only the real or the imaginary part of the complex number(s) z. Note that these new arrays are views on the original array. If you change an element in the original array, than it will also change in the new array with only the real or the imaginary part. If you don’t want this behaviour, make an explicit copy. numpy.real(z), numpy.imag(z), x = numpy.real(z).copy()
numpy.absolute()- numpy.absolute() function (numpy.abs(z)) Length of z r = numpy.abs(z)
numpy.angle() Return the angle of the complex argument. If deg=True, then return angle in degrees angles = numpy.angle(z,deg=True)
numpy.conj()- conj() function Return the complex conjugate, element-wise. The complex conjugate of a complex number is obtained by changing the sign of its imaginary part. zc = z.conjugate() # Creates a copy with changed contents
numpy.iscomplex() Returns an array with Booleans. True for every complex number. print numpy.iscomplex(z)

PART IV: Frequent errors

2. Not working csv table

Sometimes it is hard to debug a wrong csv table. The most common error is the following:

1
2
3
4
5
6
.. csv-table:: a title
   :header: "first header", "second header", "third header"
   :widths: 20, 20, 10

   "item 1" , "item 2", 3
   "item 4", "item 5", 5

After "item 1" there is space before the comma. This will cause the error. The right syntax is:

1
2
3
4
5
6
.. csv-table:: a title
    :header: "first header", "second header", "third header"
    :widths: 20, 20, 10

    "item 1", "item 2", 3
    "item 4", "item 5", 5
a title
first header second header third header
item 1 item 2 3
item 4 item 5 5

3. Not working math (or other) directive with options

When using the math directive or any other directive using options, it is important to look for simple errors. For example the following are common errors:

1
2
3
4
5
.. math:: a^2+b^2= c^2
   :label : 1

.. math:: a^2+b^2= c^2
   :label:1

The right syntax is:

.. math:: a^2+b^2= c^2
   :label: 1
(5)\[a^2+b^2= c^2\]

4. Block that does not contain all the intended text

When using the question or other block and having very long content, it is important to check if every new paragraph starts with the right indentation. The following example would contain only the first paragraph in the question block:: Note that we used option number to set the question number!

Question 25

_images/question01.png
Paragraph 1. Text Text Text Text Text Text Text Text Text Text Text Text ...

Paragraph 2. Text Text Text Text Text Text Text Text Text

The right indentation is

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
.. question::

   .. container:: questionimage

      .. image:: pictures/question01.png

   .. container:: questiontext

      Paragraph 1. Text Text Text Text Text Text Text Text Text Text Text Text ...

      Paragraph 2. Text Text Text Text Text Text Text Text Text

Question 26

_images/question01.png

Paragraph 1. Text Text Text Text Text Text Text Text Text Text Text Text ...

Paragraph 2. Text Text Text Text Text Text Text Text Text

5. Some inline text errors

When intending to make a piece of text bolded, we use **Text** to have the following effect: Text. The next rows are not correct:

** Text**
**Text **
** Text **

The same stands for the literal blocks which use the `` markup and look like this: Text. The following are incorrect:

`` Text``
``Text ``
`` Text ``

The only correct syntax is ``Text``.

The problem is analogous for the italic text, using *.