Reputation: 73
A certain python function (from the module StrawberryFields) gives me a string that contains a latex file. In short:
latex_string = function(...)
print(latex_string)
gives for example:
\documentclass{article}
\pagestyle{empty}
\usepackage{qcircuit}
\begin{document}
\Qcircuit {
& \gate{Fock} & \gate{S} & \qw & \qw \\
& \multigate{3}{\mathcal{DM}} & \qw & \multigate{1}{BS} & \qw \\
& \ghost{\mathcal{DM}} & \qw & \ghost{BS} & \qw \\
& \ghost{\mathcal{DM}} & \qw & \qw & \qw \\
& \ghost{\mathcal{DM}} & \qw & \qw & \qw \\
}
\end{document}
I can save this string to a file and open it in TeXworks via os.system(latex_string_filename), but that interrupts my python code. How do I interpret this string directly in a jupyter notebook? (That is: render the latex file, display it and continue running the notebook cell). I think this should be feasible using sympy for example, but I don't exactly know how.
Upvotes: 0
Views: 1148
Reputation: 11
Yeah, I get what you're asking for. I was also stuck at this exact situation.
You need to run the following few extra lines of code.
Although, instead of using sympy, subprocess and PIL.Image class have been used.
Also, for a Windows system, you must have 'pdflatex' and 'pdftocairo' installed.
For systems other than Windows, I don't know if there's any alternative to 'pdflatex' and 'pdftocairo'.
import subprocess
from PIL import Image
from qiskit.visualization import utils
base = prog.draw_circuit()[0] #Gets the directory path
base = base.partition('.')[0] #Removes the file extension
subprocess.run(["pdflatex",
"-halt-on-error",
f"-output-directory={base.split('/')[0]}",
f"{base.split('/')[1]}"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True)
subprocess.run(["pdftocairo",
"-singlefile",
"-png",
"-q",
base + ".pdf",
base],
check=True)
image = Image.open(base+".png")
image = utils._trim(image)
image
Note:- This code is not my innovation. It's a simplified version from the 'qiskit' module. So, all the credit goes to IBM and their developers.
To have a look at their original code, visit their github page.
Upvotes: 1