As part of a collaboration with Justin Blumenstiel at the University of Kansas, I’ve been getting reacquainted with Mathematica for the first time in many years. Although clearly one of the most powerful programming languages, I’ve always had difficulty getting comfortable with Mathematica since it is a heavily GUI based system, and GUIs make me nervous since they don’t allow the reproducibility that I am accustomed to with command line systems. Mathematica does allow execution of code at the command line through the MathKernel, but after looking around I was not able to find an easy way to convert Mathematica code generated using the GUI to something that the kernel can run cleanly. Other solutions on the web suggest converting code to Initialization Cells and saving as a “package,” but this threw a bunch of errors for me. With the help of our local Mathematica guru, I’ve now got a reasonable (albeit manual) protocol that is relatively simple and hopefully works in other contexts.

The basic trick is to convert all code generated using the GUI utilities that have pretty mathematical notation into the InputForm of the code that is read by the kernel, then save as a text file for input to MathKernel.

1) Select cells with pretty expressions and click Cell > Convert to > InputForm

2) Cut and paste the resulting inputform code into a textfile, e.g. script.m.

3) Repeat 1)-2) as needed.

4) Terminate textfile with:

Exit[]

5) Execute script from the command line prompt with:

/Applications/Mathematica.app/Contents/MacOS/MathKernel -noprompt -run “<<script.m”

The MathKernel requires absolute file paths, whereas the GUI assumes file paths start in $HOME, so be sure to use absolute file paths in the original notebook. This approach should give equivalent results to what you would obtain through the GUI, which you can check by loading the script.m and executing all the inputformat expressions into the GUI. I have however noticed very slight numerical differences (~15th significant figure) in the results from pretty and input form, which I’ll post more about if I find out the reason why.

Notes: Thanks to Michael Croucher for helping with this solution.