## How to call Mathematica from $\rm\LaTeX$?

19

5

The sagetex package for $$\rm\LaTeX$$ allows you to embed Sage code into a $$\rm\LaTeX$$ document, have that code evaluated during the .tex document processing, and then the results — numeric, symbolic, or graphical — from Sage are embedded in the pdf created by $$\rm\LaTeX$$.

Is there anything comparable for Mathematica instead of Sage?

I am aware of the MaTeX package for Mathematica, but that does just the opposite of what I'm asking: MaTeX allows $$\rm\LaTeX$$ typesetting within a Mathematica notebook.

Interesting question. You can also do what you are asking with R through Sweave and knitr. Two years ago I found the use of R in LyX documents (through knitr) very convenient, but since then I moved to using almost exclusively the R-Markdown-Pandoc combination provided by RStudio.

– Anton Antonov – 2017-07-15T18:26:50.657

7

It is also possible to call python from latex and have the output go into the latex. Here is example However, all these methods got it all the wrong way around, and they really do not work at all well in practice. The correct way to do all this is reverse the roles. Generate Latex from the program itself. Not call the program from Latex. Why? Because the Latex environment itself is not suited for using it as the container of such complex tasks. LaTex It is very fragile. Only lua can really be used with Lualatex with ease. IMHO ofcourse :)

– Nasser – 2017-07-15T20:12:20.730

4.. what I mean is that if you could find some magic way to call Mathematica from Latex, it will not be practical use and will not scale well.... – Nasser – 2017-07-15T20:21:13.253

2

Related from TeX.SX: Automatically generated plots with Mathematica.

– jkuczm – 2017-07-23T13:25:03.550

Is this what you're after? This calls W|A and Wolfram cloud: https://devpost.com/software/alphatex

– Chip Hurst – 2017-07-31T03:06:35.273

AlphaTeX is similar to what I'm after. However, unless I'm mistaken, it seems to call the online service Wolfram Alpha and not the kernel of any local copy of Mathematica. – murray – 2017-07-31T22:29:56.157

I've examined the docs that come with alphatex and haven't a clue as to where the package cloud.m should be located or how it is loaded. – murray – 2017-08-01T16:09:30.183

And running pdflatex --shell-escape medoc.tex with a \usepackage{latex alpha} and the body $\WolframAlpha{biggest city in U.S.}$ causes an error of a missing $, with no return from W|A included in the resulting .pdf. (Yes, curl is installed on my Mac.) – murray – 2017-08-01T16:19:33.973 ## Answers 10 You can use Splice, which has been superseded by FileTemplate since v10. [ As of 12.1 Splice has an entirely different meaning! ] The way it works, although all of the documentation is now gone (except that a tutorial still exists tutorial/SplicingWolframLanguageOutputIntoExternalFiles), is that in <* these kinds of matched star-angle-bracket delimiters *> you can put Mathematica code. Then invoke Splice[input_file, output_file] (and don't make them the same file!) In the few times I ever used this I called the file I wrote [whatever].mma.tex and the output [whatever].tex. Then run $$\LaTeX$$ on [whatever].tex as usual. Here is an example file, example.mma.tex: \documentclass[11pt]{article} \usepackage{graphicx} \author{evanb} \title{Splicing in Mathematica} \date{\today} % Set myPath to "/path/to/directory/containing/example.mma.tex" % <* myPath = "~/Desktop/mma_splice"; *> \begin{document} \maketitle Here we go testing the splicing ability of Mathematica: % Set up some variables that Mma sees: % <* a = 3; b = 4; c = 5; *> One example of a pythagorean triplet is <*{a,b,c}*> because we see that <*a^2*>+<*b^2*> is equal to <*a^2+b^2*>, which is the square of <*c*>. That is, $$$$a^{2}+b^{2}=c^{2}$$$$ corresponds to $$$$<*a*>^{2}+<*b*>^{2} = <*a^2*> + <* b^2 *> = <* c^2 *> = <*c*>^{2}.$$$$ You can also dynamically generate polynomials and otherwise do awesome things. Here is something that \emph{used} to work but doesn't anymore$$\ldots$$ % <*poly = x^2 + 4x + 4 *> My polynomial is $$<* poly *>$$. It factors into $$$$<*poly*>=<*Factor[poly]*>.$$$$ But we can make plots programmatically: % <* Export[myPath<>"/polyPlot.png",Plot[poly,{x,-3,3}]]; *> $$\begin{figure}[htbp] \centering \includegraphics{polyPlot} \caption{A plot of <*poly*>. You can see its zero at <*Union[Select[x/.(Solve[poly==0,x]),-3<#<3&]]*>. \label{}} \end{figure}$$ \end{document}  When, from a notebook I invoke Splice["~/Desktop/mma_splice/example.mma.tex", "~/Desktop/mma_splice/example.tex"] I wind up with a plot, polyPlot.png (because of my Export invocation), and a tex file, example.tex: \documentclass[11pt]{article} \usepackage{graphicx} \author{evanb} \title{Splicing in Mathematica} \date{\today} % For exporting the figure below, set myPath to "/path/to/directory/containing/example.mma.tex" % Null \begin{document} \maketitle Here we go testing the splicing ability of Mathematica: % Set up some variables that Mma sees: % Null One example of a pythagorean triplet is List(3,4,5) because we see that 9+16 is equal to 25, which is the square of 5. That is, $$$$a^{2}+b^{2}=c^{2}$$$$ corresponds to $$$$3^{2}+4^{2} = 9 + 16 = 25 = 5^{2}.$$$$ You can also dynamically generate polynomials and otherwise do awesome things. Here is something that \emph{used} to work but doesn't anymore$$\ldots$$ % 4 + 4*x + Power(x,2) My polynomial is $$4 + 4*x + Power(x,2)$$. It factors into $$$$4 + 4*x + Power(x,2)=Power(2 + x,2).$$$$ But we can make plots programmatically: % Null $$\begin{figure}[htbp] \centering \includegraphics{polyPlot} \caption{A plot of 4 + 4*x + Power(x,2). You can see its zero at List(-2). \label{}} \end{figure}$$ \end{document}  which can then be run through pdflatex example.tex to produce a PDF (which I can't seem to embed here, but imgur uploaded it OK: http://imgur.com/a/yFRMM ). I also can't get TeXForm or anything to work in a way that I expect. This used to work better, I think? Anyway, you may be better off learning how to use FileTemplate. Rather than opening a notebook to invoke Splice, I would wager you could do it via invoking Mathematica on the command line---shouldn't be too tough. I've never used FileTemplate but it looks like some similar things can be done. For example, it looks like it supports <*expr*> kind of notation. – evanb – 2017-08-30T13:02:20.437 And it may be possible to use ExportString rather than TeXForm. – evanb – 2017-08-30T13:04:38.923 Splice is not working for me with Mathematica 11.1 (under macOS) with your example.mma.tex: no polyPlot file is produced when I run the same Splice command you showed, and so of course (pdf)LaTeX stops with an error at \includegraphics{polyPlot} when I process the output file example.tex that Splice produced. – murray – 2017-08-31T15:24:09.307 That's weird. I have $VersionString="11.1.0 for Mac OS X x86 (64-bit) (March 16, 2017)" – evanb – 2017-08-31T16:29:19.403

Is example.mma.tex located in the folder ~/Desktop/mma_splice? If not, change myPath on the 7th line and try again. – evanb – 2017-08-31T16:30:40.690

BTW, I'm not sure what happens if you invoke something like NotebookDirectory[] in the spliced file. – evanb – 2017-08-31T16:32:18.747

Yes, example.mma.tex is in ~/Desktop/mma_splice. In that source file, you have a comment about setting path. Setting path for what? – murray – 2017-08-31T16:57:45.200

And you do get an example.tex produced? The myPath variable encodes where where the polyPlot.png will be produced (look at the Export of the figure). – evanb – 2017-08-31T19:25:50.207

Yes, example.tex is produced. But when I process it in LaTeX, there is no file polyPlot.png in the same folder (or anywhere else). – murray – 2017-09-01T17:44:23.123

Hm. Then I don't know what to say. You can try running an Export statement from a notebook. Other than that I'm stumped. – evanb – 2017-09-04T15:45:27.870

4

You're probably better off coding your figures/tables/etc. in Mathematica and simply exporting as PDF and $\TeX$. You can use StringTemplate, TeXForm, Export and ExportString to generate $\TeX$ input. There's no Mathematica wrapper for $\LaTeX$ that I'm aware of, though you could look into Sage's Mathematica bindings and use those in the aforementioned Sage $\LaTeX$ environment if you're really determined.

4

You may find this collection of Python scripts useful. It does the job you are asking for -- it allows you to include Mathematica code and output in your LaTeX source. The source and examples can be found at https://github.com/leo-brewin/hybrid-latex

Here is a short example (based on example-01 from the GitHub site)

\documentclass[12pt]{mmalatex}

\begin{document}

\section*{Calculus}

$$\begin{mathematica} ans = D[x Sin[x],x] (* mma (ans.501,ans) *) ans = D[x Sin[x],x]/.x -> Pi/4 (* mma (ans.502,ans) *) ans = Integrate[2 Sin[x]^2, {x, a, b}] (* mma (ans.503,ans) *) ans = Integrate[2 Exp[-x^2],{x, 0, Infinity}] (* mma (ans.504,ans) *) ans = HoldForm[Integrate[2 Exp[-x^2], {x, 0, Infinity}]] (* mma (lhs.504,ans) *) ans = Integrate[x^2 + y^2, {x, 0, 1}, {y, 0, x}] (* mma (ans.505,ans) *) ans = HoldForm[Integrate[x^2 + y^2, {x, 0, 1}, {y, 0, x}]] (* mma (lhs.505,ans) *) \end{mathematica}$$

\begin{align*} &\mma*{ans.501}\\ &\mma*{ans.502}\\ &\mma*{ans.503}\\ \mma{lhs.504}&=\Mma{ans.504}\\ \mma{lhs.505}&=\Mma{ans.505} \end{align*}

\end{document}


And here is a png of the output

Could you please include a short demo in the answer itself? – Szabolcs – 2018-09-27T07:50:44.607

I've edited my answer to contain a short example. – user60392 – 2018-09-28T08:38:41.870

I don't understand the config after installing your files: while my python3 is in /usr/local/bin, trying "pylatex.sh -i example-01" gives 'Traceback error for File "example-01_.py", line 11, in <module> from sympy import * ImportError: No module named sympy". How am I supposed to give access to sympy, as the methods recommended at docs.sympy.org are to use anaconda (which I have installed and which includes sympy) that seems to create a python-related file tree, including the python3 binary, in a different place from /usr/local/bin, namely, in /Applications/anaconda3. – murray – 2018-09-29T20:22:50.677

I'm guessing the your still picking up your non-anaconda environment for python. You can either add /Applications/ananconda3/bin to your \$PATH (ahead of any other python) or you could try "pylatex.sh -i example-01 -P/Applications/anaconda3/bin/python3" – user60392 – 2018-09-30T23:13:58.363

3

I'm no Latex expert; however I have had some success with calling WolframScript from within a Tex document. The premise of my approach is to execute a script that exports some TeX fragment or an image. The script is generated in situ, then executed and read at the appropriate point. I use this approach to generate personalized quizzes for students; I can simply search for and replace the random seed and re-run the document. It does require that shell escape has been implemented.

\newcommand{\imwr}{\immediate\write18}
$$\begin{filecontents*}{temp.wl} seed = 1211; SeedRandom[seed]; t = TableForm[{ {"feedback resistor", RandomChoice[{"0.8", "0.9", "1", "1.1", "1.2"}] <> " MOhm"}, {"internal resistance of phototube", RandomChoice[{"3", "4", "5"}] <> " x10^4 Ohm"}, {"amplifier open-loop gain", RandomChoice[{"0.9", "1.0", "1.1"}] <> " x10^5"} }]; Export["wlout.tex", t, "TexFragment"]; \end{filecontents*}$$

\imwr {wolframscript -file temp.wl}

\input{wlout}