Simple python to LaTeX parser

We demo a script that converts python numerical commands to LaTeX format. A notebook available on our GitHub page will take this and pretty print the result.

Follow us on twitter for new submission alerts!

Introduction

Here, we provide a simple script that accepts numerical python commands in string format and converts them into LaTeX markup. An example input / output follows:

If the output shown here is plugged into a LaTeX editor, we get the following result:

Our Jupyter notebook automatically pretty prints to this form.

We provide the script here as it may be useful for two sorts of applications: 1) facilitating write-ups of completed projects, and 2) visualizing typed-up formulas to aid checks of their accuracy. The latter is particularly helpful for lengthy commands, which are often hard to read in python format.

We note that the python package sympy also provides a simple command-to-latex parser. However, I have had trouble getting it to output results if any functions appear that have not been defined — we illustrate this issue in the notebook.

As usual, our code can be downloaded from our github page here.

Code

The main code segment follows. The method command_to_latex recursively computes the LaTeX for any combinations of variables grouped together via parentheses. The base case occurs when there are no parentheses left, at which point the method parse_simple_eqn is called, which converts simple commands to LaTeX. The results are then recombined within the recursive method. Additional replacements can be easily added in the appropriate lines below.

That’s it!