20
$\begingroup$

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.

$\endgroup$
8
  • $\begingroup$ 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. $\endgroup$ Jul 15, 2017 at 18:26
  • 7
    $\begingroup$ 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 :) $\endgroup$
    – Nasser
    Jul 15, 2017 at 20:12
  • 4
    $\begingroup$ .. 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.... $\endgroup$
    – Nasser
    Jul 15, 2017 at 20:21
  • 2
    $\begingroup$ Related from TeX.SX: Automatically generated plots with Mathematica. $\endgroup$
    – jkuczm
    Jul 23, 2017 at 13:25
  • $\begingroup$ Is this what you're after? This calls W|A and Wolfram cloud: devpost.com/software/alphatex $\endgroup$
    – Greg Hurst
    Jul 31, 2017 at 3:06

4 Answers 4

10
$\begingroup$

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,
\begin{equation}
	a^{2}+b^{2}=c^{2}
\end{equation}
corresponds to
\begin{equation}
	<*a*>^{2}+<*b*>^{2} = <*a^2*> + <* b^2 *> = <* c^2 *> = <*c*>^{2}.
\end{equation}
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
\begin{equation}
	<*poly*>=<*Factor[poly]*>.
\end{equation}
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,
\begin{equation}
	a^{2}+b^{2}=c^{2}
\end{equation}
corresponds to
\begin{equation}
	3^{2}+4^{2} = 9 + 16 = 25 = 5^{2}.
\end{equation}
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
\begin{equation}
	4 + 4*x + Power(x,2)=Power(2 + x,2).
\end{equation}
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: https://i.stack.imgur.com/6tyqx.jpg ). 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.

$\endgroup$
10
  • $\begingroup$ 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. $\endgroup$
    – evanb
    Aug 30, 2017 at 13:02
  • $\begingroup$ And it may be possible to use ExportString rather than TeXForm. $\endgroup$
    – evanb
    Aug 30, 2017 at 13:04
  • $\begingroup$ 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. $\endgroup$
    – murray
    Aug 31, 2017 at 15:24
  • $\begingroup$ That's weird. I have $VersionString="11.1.0 for Mac OS X x86 (64-bit) (March 16, 2017)" $\endgroup$
    – evanb
    Aug 31, 2017 at 16:29
  • $\begingroup$ Is example.mma.tex located in the folder ~/Desktop/mma_splice? If not, change myPath on the 7th line and try again. $\endgroup$
    – evanb
    Aug 31, 2017 at 16:30
4
$\begingroup$

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.

$\endgroup$
4
$\begingroup$

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

output from above latex source

$\endgroup$
4
  • $\begingroup$ Could you please include a short demo in the answer itself? $\endgroup$
    – Szabolcs
    Sep 27, 2018 at 7:50
  • $\begingroup$ I've edited my answer to contain a short example. $\endgroup$
    – user60392
    Sep 28, 2018 at 8:38
  • $\begingroup$ 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. $\endgroup$
    – murray
    Sep 29, 2018 at 20:22
  • $\begingroup$ 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" $\endgroup$
    – user60392
    Sep 30, 2018 at 23:13
3
$\begingroup$

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}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.