# Computation Results in LaTeX

For my laboratory reports, I like to write Python programs that do all the calculations and plotting for me. To get the results from the program into my LaTeX document, I use a Python templating system, Jinja.

Over the time, I have refined this a bit. You can only read the first section if you want to get started quickly.

## The basic version

So the report might look like so:

We measured the voltage $U = \SI{<< u_val >> \pm << u_err >>}{\volt}$ and the
current $I = \SI{<< i_val >> \pm << i_err >>}{\ampere}$. Then we computed the
resistance $R = \SI{<< r_val >> \pm << "%.2f" % r_err >>}{\ohm}$.

All our measurements:
\begin{table}[h]
\begin{tabular}{SS}
{$U$} & {$I$} \\
\hline
%< for u, i in data: ->%
\SI{<< u >>}\volt & \SI{<< i >>}\ampere \\
%< endfor ->%
\end{tabular}
\end{table}


I changed the default variable delimiters from {{ and }} to << and >>. And the {% and %} became %< and >%. That way, at least the latter will become plain comments.

Now in the Python program, I will do my calculation in the namespace of the main method. The template is then rendered with **locals(), which gives the complete local namespace to the template. This is probably not very clean, but I can use the exact same variables in the document.

import jinja2
import math

def main():
# Setting up Jinja
env = jinja2.Environment(
"%<", ">%",
"<<", ">>",
"[§", "§]",
)
template = env.get_template("article.tex")

# Measurements.
u_val = 6.2
u_err = 0.1

i_val = 2.0
i_err = 0.1

data = [
(3, 4),
(1, 4.0),
(5, 1),
]

# Calculations
r_val = u_val / i_val
r_err = math.sqrt(
(1/i_val * u_err)**2
+ (u_val/i_val**2 * i_err)**2
)

# Rendering LaTeX document with values.
with open("out.tex", "w") as f:
f.write(template.render(**locals()))

if __name__ == "__main__":
main()


The result in out.tex looks like so:

We measured the voltage $U = \SI{6.3 \pm 0.1}{\volt}$ and the
current $I = \SI{2.0 \pm 0.1}{\ampere}$. Then we computed the
resistance $R = \SI{3.15 \pm 0.17}{\ohm}$.

All our measurements:
\begin{table}[h]
\begin{tabular}{SS}
{$U$} & {$I$} \\
\hline
\SI{3}\volt & \SI{4.0}\ampere \\
\SI{1}\volt & \SI{4.0}\ampere \\
\SI{5}\volt & \SI{1.0}\ampere \\
\SI{7}\volt & \SI{4.0}\ampere \\
\end{tabular}
\end{table}


Together with a small makefile:

out.pdf: out.tex


## Using unitprint

For these documents, I wrote python3-unitprint which can format numbers with errors nicely. Then in the Python program I write something like:

E_val = ...
E_err = ...
T['E'] = unitprint.siunitx(E_val, E_err)


This will format the numbers in a way that the siunitx LaTeX package can understand. In the template I then use the following:

The energy $E$ is \SI{<< E >>}{\joule}.


Since the value and error are included in the same variable in the template, one does not have to use „±" by hand. This makes the template cleaner.