A Software Tool for Typesetting Quizzes

Hans Petter Langtangen [1, 2]

[1] Center for Biomedical Computing, Simula Research Laboratory
[2] Department of Informatics, University of Oslo

Mar 30, 2015

Summary. This note describes a system for writing quizzes (multiple-choice questions) in a compact text format with support for mathematics, computer code, and flexible formatting. The text format can be automatically translated to HTML and to a Python data structure. The HTML can be rendered directly in web pages, and the data structure can (in the future) be fed to online quiz/survey services a la Kahoot, JotForm, and Google forms.

A pure text quiz

Question and choices

Here is a typical quiz with a question and four alternative answers:

Question: What is the capital of Norway?

Choice 1: Helsinki

Choice 2: Drammen

Choice 3: Oslo

Choice 4: Denmark

The above quiz can be specified by the compact text

!bquiz
Q: What is the capital of Norway?
Cw: Helsinki
Cw: Drammen
Cr: Oslo
Cw: Denmark
!equiz

Syntax:

Multiple correct choices are possible. Here is an example with three right choices:

!bquiz
Q: Which of the following cities are capitals?
Cw: Sidney
Cr: Kigali
Cw: Bonn
Cr: Bern
Cr: Ottawa
Cw: New York
!equiz

Question: Which of the following cities are capitals?

Choice 1: Sidney

Choice 2: Kigali

Choice 3: Bonn

Choice 4: Bern

Choice 5: Ottawa

Choice 6: New York

Explanations of choices

Sometimes it is desireable to give some explanation why certain choices are wrong (or right).

Question: What is the capital of Norway?

Choice 1: Helsinki

Choice 2: Drammen

Choice 3: Oslo

Choice 4: Denmark

The quiz syntax applies E: ... after the choice to give an explanation of that choice.

!bquiz
Q: What is the capital of Norway?

Cw: Helsinki
E: Helsinki is the capital of Finland.

Cw: Drammen
E: Drammen is a small city close to Oslo.

Cr: Oslo

Cw: Denmark
!equiz

This time we also added some whitespace for enhanced reading of the text.

Typesetting

It is easy to use emphasize font, boldface, color, hyperlinks, etc., since the text in the specification of questions, choices, and explanations are rendered according to the DocOnce markup language. For simple typesetting (emphasize, boldface, links) DocOnce also accepts Markdown syntax. Here is an example:

Question: This is a very famous quote:

Premature optimization is the root of all evil.
This quote is attributed to

Choice 1: Geroge W. Bush

Choice 2: Donald Knuth

Choice 3: Ole-Johan Dahl

The corresponding specification reads

!bquiz
Q: Here is a famous quote:

!bquote
*Premature optimization is the root of all evil.*
!equote
This quote is attributed to

Cw: Geroge W. Bush

Cr: Donald Knuth
E: According to "Wikiquote": "http://en.wikiquote.org/wiki/Donald_Knuth",
Donald Knuth wrote this statement in *Structured Programming with
Goto Statements*. Computing Surveys, _6_:4,
pp. 261-301, _1974_.

Cw: Ole-Johan Dahl
E: Ole-Johan Dahl was a famous Norwegian professor of computer
science and together with Kristen Nygaard the inventor of
object-oriented programming, but he is not the man behind this
quote.
!equiz

Quiz inside admonitions

Question admonitions may well feature quizzes unless the output format is reStructuredText (rst, sphinx). A plain question admonition is

Question.

What is the capital of Norway?

specified by the DocOnce syntax

!bquestion
What is the capital of Norway?
!equestion

Putting a quiz inside the question admonition looks like

Question.

What is the capital of Norway?

Answer: Stockholm

Choice 2: Bergen

Choice 3: Oslo

Choice 4: Denmark

specified as

!bquestion
!bquiz
Q: [] What is the capital of Norway?

Cw: [Answer:] Stockholm
E: Stockholm is the capital of Sweden, Norway's neighboring country.

Cw: Bergen
E: Some people from Bergen may claim so... It is just the second
largest city in Norway.

Cr: Oslo

Cw: Denmark
!equiz
!equestion

Choice and question prefix.

In the above example, we demonstrate the possibility to control the word preceding the question and the choices. For the current output format (html), questions are by default preceded by Question: and choices by Choice X:, where X is the number of the choice.

The prefix appears inside square brackets. Empty brackets, as those in the question, leads to no prefix. The choice Stockholm has a prefix [Answer:], and exactly the text inside the square brackets precedes the text of this choice in the output.

Typesetting of mathematics and computer code

Mathematics

Typesetting of mathematics in a quiz follows a restricted LaTeX syntax. Inline formulas appear inside dollar signs, while separate equations appear inside !bt ("begin TeX") and !et ("end TeX") tags.

Simple example

Question: Compute the result of \( a+b \) in the case \( a=2 \) and \( b=2 \).

Choice 1: 5.

Choice 2: 4.

Choice 3: The computation does not make sense when \( a \) and \( b \) are given without units.

The source code for defining the above quiz reads

!bquiz
Q: Compute the result of $a+b$ in the case $a=2$ and $b=2$.

Cw: 5.

E: Good attempt, especially when referring to the following story.

!bquote
An anthropologist was asking a primitive tribesman about arithmetic.
When the anthropologist asked, *What does two and two make?* the
tribesman replied, *Five.* Asked to explain, the tribesman said, *If I
have a rope with two knots, and another rope with two knots, and I
join the ropes together, then I have five knots.*
!equote

Cr: 4.
E: Seems trivial, but once upon a time...

FIGURE: [fig/1p1, width=180 frac=0.3]

Cw: The computation does not make sense when $a$ and $b$ are given without
units.

E: It is indeed possible to add pure numbers without any units.
!equiz

Only a subset of all LaTeX equation environments is supported!

To make sure blocks with equations come out correctly in different output formats (LaTeX, HTML, Sphinx, Markdown), only four types of standard LaTeX equation environments should be used:

  1. Single equation without number: \[ ... \] or equation* environment
  2. Single equation with number: equation environment
  3. Multiple, aligned equations without numbers: align* environment
  4. Multiple, aligned equations with numbers: align environment
This means that one has to stay away from eqnarray, alignat, and other common LaTeX equation environments. However, inside an equation, standard LaTeX math typesetting works (like \alpha, \mbox{...}, etc.).

A more complicated example

Question: The equation $$ \begin{equation} \nabla\cdot\boldsymbol{u} = 0 \label{cont:eq} \end{equation} $$ is famous in physics. Select the wrong assertion(s):

Choice 1: The equation tells that the net outflow of something with velocity \( \boldsymbol{u} \) in region is zero.

Choice 2: The equation tells that the vector field \( \boldsymbol{u} \) is divergence free.

Choice 3: The equation implies that there exists a vector potential \( \boldsymbol{A} \) such that \( \boldsymbol{u}=\nabla\times\boldsymbol{A} \).

Choice 4: The equation implies \( \nabla\times\boldsymbol{u}=0 \).

Choice 5: The equation implies that \( \boldsymbol{u} \) must be a constant vector field.

The corresponding code needed to define this quiz is listed below. Note two new features:

Keywords and label should appear before or right after the question and they cannot span more than one line.

Now we present the complete code for the quiz above:

!bquiz
Q: The equation

!bt
\begin{equation}
\nabla\cdot\boldsymbol{u} = 0
label{cont:eq}
\end{equation}
!et
is famous in physics. Select the wrong assertion(s):

K: gradient; divergence; curl; vector calculus
L: div:assert

Cw: The equation tells that the net outflow of something with
velocity $\boldsymbol{u}$ in region is zero.
E: This is right: integrating \eqref{cont:eq} over an arbitrary domain
$\Omega$ and using Gauss' divergence theorem, we get the surface integral

!bt
\[ \int_{\partial\Omega}\boldsymbol{u}\cdot\boldsymbol{n}dS=0,\]
!et
where $\boldsymbol{n}$ is an outward unit normal on the boundary $\partial\Omega$.
The quantity $\boldsymbol{u}\cdot\boldsymbol{n}dS$ is the outflow of volume per
time unit if $\boldsymbol{u}$ is velocity.

Cw: The equation tells that the vector field $\boldsymbol{u}$ is divergence free.
E: Yes, *divergence free* is often used as synonym for *zero divergence*,
and $\nabla\cdot\boldsymbol{u}$ is the divergence of a vector field $\boldsymbol{u}$.

Cw: The equation implies that there exists a vector potential $\boldsymbol{A}$
such that $\boldsymbol{u}=\nabla\times\boldsymbol{A}$.
E: Yes, this is an important result in vector calculus that is much
used in electromagnetics.

Cr: The equation implies $\nabla\times\boldsymbol{u}=0$.
E: No, only if $\boldsymbol{u}=\nabla\phi$, for some scalar potential $\phi$,
we have $\nabla\times\boldsymbol{u}=0$.

Cr: The equation implies that $\boldsymbol{u}$ must be a constant vector field.
E: No, it is the *sum* of derivatives of different components of $\boldsymbol{u}$
that is zero. Only in one dimension, where $\boldsymbol{u}=u_x\boldsymbol{i}$
and consequently $\nabla\cdot\boldsymbol{u}=du/dx$, the vector field must be constant.
!equiz

Computer code

Inline computer code (variables, expressions, statements) are normally typeset with a monospace font, and this is enabled by enclosing the code in backticks. Blocks of computer code are typeset with !bc ("begin code") and !ec ("end code") tags. One can specify the computer language as part of the !bc tag: !bc LX, where L is the language (py for Python, m for Matlab, cpp for C++, for instance) and X can be pro for a complete executable program or cod for a code snippet (cannot be executed without additional statements) [1]. The quizzes below demonstrate the syntax.

1: X can also be hide for code that is not supposed to be shown, but possibly required to execute other snippets in an interactive document (that allows code to be edited and executed by the reader). This is currently being implemented in DocOnce's support for Runestone Interactive books (using the Sphinx format).

Question: We want to create a Python list object of length n where each element is 0. Is the following code then what we need?

import numpy
mylist = numpy.zeros(n)

Choice 1: Yes.

Choice 2: Yes, provided we write np instead of numpy:

import numpy as np
mylist = np.zeros(n)

Choice 3: No.

!bquiz
Q: We want to create a Python list object of length `n` where each
element is `0`. Is the following code then what we need?

!bc pycod
import numpy
mylist = numpy.zeros(n)
!ec

K: list, array

Cw: Yes.

E: Not exactly: `numpy.zeros` creates an array of zeros, not a list.

Cw: Yes, provided we write `np` instead of `numpy`:

!bc pycod
import numpy as np
mylist = np.zeros(n)
!ec

E: No, this is fully equivalent to the original code, so `mylist` becomes
an array, not a list.

Cr: No.
E: One would need to do `mylist = [0]*n` or `numpy.zeros(n).tolist()`.
!equiz

Summary of quiz syntax:

Example: Putting it all together

Question:

from math import sin

def D(u, t, dt=1E-5):
    return (u(t + dt) - u(t - dt))/(2*dt)

def u(t):
    "A quadratic function."
    return t^2

print D(u, t=4),
print D(lambda x: return 2*x, 2)

The purpose of this program is to differentiate the two mathematical functions $$ \begin{align*} u(t) &= t^2,\\ f(x) &= 2x. \end{align*} $$ Determine which of the following assertions that is wrong.

Choice 1: In Python, the syntax for \( t^2 \) is t**2, not t^2, so the u function contains an error.

Choice 2: The string in the u function is a valid doc string.

Choice 3: The output from the program is on a single line, despite two print statements.

Choice 4: One cannot use u both inside the D function and in the outer calling code (the main program).

Choice 5: The call D(lambda x: return 2*x, 2) is equivalent to defining

def f(x):
    return 2*x

and then calling D(f, 2).

Choice 6: There is danger of integer division in the D function.

Choice 7: The D function computes an approximate derivative of the function u(t).

Choice 8: Both calls to D results in the exact derivative, provided we replace t^2 by t**2.

Specification in HTML

Instead of using the compact text specification with DocOnce formatting, one can use a more verbose syntax and specify everything in HTML. The second example in the section Mathematics goes as follows with HTML syntax.

 <!-- --- begin quiz --- -->
 <!-- --- begin quiz question --- -->
 The equation

 $$
 \begin{equation}
 \nabla\cdot\boldsymbol{u} = 0
 \label{cont:eq}
 \end{equation}
 $$

 is famous in physics. Select the wrong assertion(s):
 <!-- --- end quiz question --- -->
 <!-- --- keywords:['gradient', 'divergence', 'curl', 'vector calculus'] -->
 <!-- --- label:div:assert -->

 <!-- --- begin quiz choice 1 (wrong) --- -->
 The equation tells that the net outflow of something with
 velocity \( \boldsymbol{u} \) in region is zero.
 <!-- --- end quiz choice 1 (wrong) --- -->

 <!-- --- begin explanation of choice 1 --- -->
 This is right: integrating \eqref{cont:eq} over an arbitrary
 domain \( \Omega \) and using Gauss' divergence theorem, we
 get the surface integral

 $$ \int_{\partial\Omega}\boldsymbol{u}\cdot\boldsymbol{n}dS=0,$$

 where \( \boldsymbol{n} \) is an outward unit normal on the
 boundary \( \partial\Omega \).
 The quantity \( \boldsymbol{u}\cdot\boldsymbol{n}dS \) is the
 outflow of volume per time unit if \( \boldsymbol{u} \) is
 velocity.
 <!-- --- end explanation of choice 1 --- -->

 <!-- --- begin quiz choice 2 (wrong) --- -->
 The equation tells that the vector field \( \boldsymbol{u} \)
 is divergence free.
 <!-- --- end quiz choice 2 (wrong) --- -->

 <!-- --- begin explanation of choice 2 --- -->
 Yes, <em>divergence free</em> is often used as synonym for
 <em>zero divergence</em>, and \( \nabla\cdot\boldsymbol{u} \)
 is the divergence of a vector field \( \boldsymbol{u} \).
 <!-- --- end explanation of choice 2 --- -->

 <!-- --- begin quiz choice 3 (wrong) --- -->
 The equation implies that there exists a vector potential
 \( \boldsymbol{A} \) such that
 \( \boldsymbol{u}=\nabla\times\boldsymbol{A} \).
 <!-- --- end quiz choice 3 (wrong) --- -->

 <!-- --- begin explanation of choice 3 --- -->
 Yes, this is an important result in vector calculus that is much
 used in electromagnetics.
 <!-- --- end explanation of choice 3 --- -->

 <!-- --- begin quiz choice 4 (right) --- -->
 The equation implies \( \nabla\times\boldsymbol{u}=0 \).
 <!-- --- end quiz choice 4 (right) --- -->

 <!-- --- begin explanation of choice 4 --- -->
 No, only if \( \boldsymbol{u}=\nabla\phi \), for some scalar
 potential \( \phi \), we have \( \nabla\times\boldsymbol{u}=0 \).
 <!-- --- end explanation of choice 4 --- -->

 <!-- --- begin quiz choice 5 (right) --- -->
 The equation implies that \( \boldsymbol{u} \)
 must be a constant vector field.
 <!-- --- end quiz choice 5 (right) --- -->

 <!-- --- begin explanation of choice 5 --- -->
 No, it is the <em>sum</em> of derivatives of different components
 of \( \boldsymbol{u} \) that is zero. Only in one dimension,
 where \( \boldsymbol{u}=u_x\boldsymbol{i} \) and consequently
 \( \nabla\cdot\boldsymbol{u}=du/dx \), the vector field must be
 constant.
 <!-- --- end explanation of choice 5 --- -->
 <!-- --- end quiz --- -->

This syntax applies begin-end comments to mark the start and end of the question, the choices, and the explanations.

Warning.

The HTML specification of a quiz is not a meaningful HTML code for displaying the quiz in a browser, it is just an application of the HTML language to specify information and have full control of the typesetting details. Some program must interpret the HTML above and typset questions, choices, and explanations adequately.

The Python data structure for quizzes

When a DocOnce file mydoc.do.txt containing quizzes (and other types of text, like this document) is translated to some format by the doconce format command, a Python list of all the quizzes is created and written to .mydoc.quiz. Each list element represents one quiz as a dictionary. The list corresponding to the quizzes in the current document starts with

[{'choices': [[u'wrong', u'Helsinki'],
              [u'wrong', u'Drammen'],
              [u'right', u'Oslo'],
              [u'wrong', u'Denmark']],
  'no': 1,
  'question': u'What is the capital of Norway?'},

A more complicated quiz with specification of prefix for the question and one choice (see example above in the question admonition) has explanations in the list for each choice, as well as two more keys (choice prefix and question prefix):

 {'choice prefix': [u'Answer:', None, None, None],
  'choices': [
    [u'wrong',
     u'Stockholm',
     u"Stockholm is the capital of Sweden, Norway's neighboring country."],
    [u'wrong',
     u'Bergen',
     u'Some people from Bergen may claim so... It is just the second\nlargest city in Norway.'],
    [u'right', u'Oslo'],
    [u'wrong', u'Denmark']],
  'no': 5,
  'question': u'What is the capital of Norway?',
  'question prefix': u''},

The text in the Python list-dictionary data structure is ready-made for being displayed in HTML. Here is an example involving mathematics (MathJax syntax):

 {'choices': [
   [u'wrong',
    u'5.',
    u'Good attempt, especially when referring to the following story.
\n\n<p>\n<blockquote>\n    An anthropologist was asking a primitive tribesman ab
out arithmetic.\n    When the anthropologist asked, <em>What does two and two ma
ke?</em> the\n    tribesman replied, <em>Five.</em> Asked to explain, the tribes
man said, <em>If I\n    have a rope with two knots, and another rope with two kn
ots, and I\n    join the ropes together, then I have five knots.</em>\n</blockqu
ote>'],
   [u'right',
    u'4.',
    u'Seems trivial, but once upon a time...\n\n<p>\n<center><p><img src="fig/1p1.gif" align="bottom" width=180></p></center>'],
   [u'wrong',
    u'The computation does not make sense when \\( a \\) and \\( b \\) are given without\nunits.',
    u'It is indeed possible to add pure numbers without any units.']],
  'no': 6,
  'question': u'Compute the result of \\( a+b \\) in the case \\( a=2 \\) and \\( b=2 \\).'},

Computer code gets typeset by nice colors by default (using the Pygments package):

{'choices':
   [[u'wrong',
     u'Yes.',
     u'Not exactly: <code>numpy.zeros</code> creates an array of zeros
, not a list.'],
    [u'wrong',
     u'Yes, provided we write <code>np</code> instead of <code>numpy</code>:\n\n<p>\n\n<!-- code=python (!bc pycod) typeset with pygments style "default" -->\n<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>\nmylist <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)\n</pre></div>\n<p>',
     u'No, this is fully equivalent to the original code, so <code>mylist</code> becomes\nan array, not a list.'],
    [u'right',
     u'No.',
     u'One would need to do <code>mylist = [0]*n</code> or <code>numpy.zeros(n).tolist()</code>.']],
  'no': 8,
  'question': u'We want to create a Python list object of length <code>n</code> where each\nelement is <code>0</code>. Is the following code then what we need?\n\n<p>\n\n<!-- code=python (!bc pycod) typeset with pygments style "default" -->\n<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span>\nmylist <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>zeros(n)\n</pre></div>\n<p>'}

The keys in the dictionaries in this data structure are

Translating the quiz format to HTML or PDF

The program doconce must be run to interpret the quiz format, translate it to LaTeX, HTML, or other formats, and produce the Python representation of the collection of quizzes in a document. Let the name of the document with quiz specifications and optional text be myquiz.do.txt. Documents to play around with are pure_quiz.do.txt or the present document.

HTML

Plain HTML

A simple HTML rendering of quizzes is done by

Terminal> doconce format html myquiz

The result myquiz.html can be loaded into a browser.

Bootstrap HTML

A more sophisticated rendering is offered if a Bootstrap HTML style is adopted,

Terminal> doconce format html myquiz --html_style=bootstrap

Other variations of this class of styles are bootswatch, and bootswatch_X, where X is the name of a Bootswatch style, e.g., journal.

The Bootstrap-based styles have a striking red color for inline computer code, which can be avoided by giving the option --html_code_style=inherit (see the documentation of DocOnce and Bootstrap for details and examples).

By default, there is a horizontal rule enclosing each quiz in the HTML format. This can be turned off by the option --quiz_horizontal_rule=off.

Multiple page HTML document

By inserting !split before headings in a DocOnce document, one can run

Terminal> doconce split_html myquiz.html

to create a multi-page document with navigation arrows. Bootstrap styles will also have a Contents pull-down menu to the right in the top bar. Without the split_html command (and !split instructions in the document), all quizzes will be in one HTML page.

Setting the question and choice prefix

The prefix before a question is Question: and before a choice is Choice X, where X is a number. To set a different prefix, see the --quiz_question_prefix and --quiz_choice_prefix commands when running doconce format --help.

LaTeX

The standard command to produce a LaTeX document is

Terminal> doconce format pdflatex myquiz \ 
          --without_answers --without_solutions \ 
          --latex_code_style=pyg

If desired, the correct answer to each quiz can be included by omitting --without_answers. Omitting --without_solutions will print the right answers and the available explanations below the quiz.

The next step is to compile the document:

Terminal> pdflatex -shell-escape myquiz

to produce a PDF myquiz.pdf. Here, we use the pyg (Pygments, LaTeX package minted) style for code blocks, which requires the -shell-escape option when running pdflatex.

Sphinx

A typical session for creating a Sphinx document is

Terminal> doconce format sphinx myquiz
Terminal> doconce split_rst myquiz
Terminal> doconce sphinx_dir dirname=sphinx theme=default myquiz
Terminal> python automake_sphinx.py

A disadvantage of Sphinx in a quiz context is that admonitions cannot contain quizzes. However, an advantage of Sphinx is that one can create RunestoneInteractive Sphinx books, which have nice browser support of quizzes. A RunestoneInteractive version is created by

Terminal> doconce format sphinx myquiz --runestone
Terminal> doconce split_rst myquiz
Terminal> doconce sphinx_dir dirname=sphinx theme=default myquiz
Terminal> python automake_sphinx.py --runestone