iPython Notebook output latex or mathjax - python

How do you get iPython to output results using latex?
For example, like on this page: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/master/examples/notebooks/SymPy%20Examples.ipynb
If I execute the code:
Rational(3,2)*pi + exp(I*x) / (x**2 + y)
I get output:
Out[13]: 3*pi/2 + exp(I*x)/(x**2 + y)
I want to see output in latex as shown in the link above.

An updated answer for those googlers:
from IPython.display import Math
Math('3 \cdot \\frac{\pi}{2} + e^{\\frac{I*x}{x^2 + y}}')
A bit more clumsy than SymPy, but doesn't need an extra package.

As done in the link you posted and mentioned by #tcaswell you need to "activate" the latex printing using
from sympy.interactive import printing
printing.init_printing(use_latex=True)
the use_latex=True statement is required with sympy 0.7.2 but not with 0.7.3.

Related

How to render math symbols as text in SVG/EPS/PDF images?

When creating graphs using, for instance, Python. It is possible to save these figures as vector graphics (SVG, EPS, PDF) and the text is rendered separately. This makes it possible to select or search the text when shown in a pdf file. However, I've tried to render a simple graph using math symbols in addition to text (in latex). The math symbol gets encoded as part of the image, rather than as text.
Here is a minimum reproducible example.
import numpy as np
import matplotlib.pyplot as plt
x_list = np.linspace(-10,10,num=128)
y = list(map(lambda x: (x**2 + x + 1), x_list))
plt.plot(y, label="$\\Psi_{example}$")
plt.legend()
plt.xticks(np.linspace(0, 128, num=8),
map(round, np.linspace(-10, 10, num=8), [0] * 8))
plt.savefig("./example.pdf")
Which produces the following image.
When saving this image as vector graphics, all the numbers as well as the 'example' word in the legend become selectable/searchable (i.e. rendered as text). However, the Ψ (Psi) character is not selectable/searchable.
Is there any way to make math symbols render as text in vector graphics?
I have been able to get it to work in the way I think you want by first installing a LaTeX distribution (I used MikTex, from here) and then setting the matpotlib option to use LaTeX to render your symbols and text.
Note that after installing MikTex, I had to open a new instance of my command prompt or code editor to make sure it was aware of the change to my PATH and where the LaTex is installed.
I added the import and mpl.rcParams line to your example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
x_list = np.linspace(-10, 10, num=128)
y = list(map(lambda x: (x**2 + x + 1), x_list))
plt.plot(y, label="$\\Psi_{example}$")
plt.legend()
plt.xticks(np.linspace(0, 128, num=8),
map(round, np.linspace(-10, 10, num=8), [0] * 8))
plt.savefig("./example.pdf")
It's two different matters. Characters are represented by codes. In this case, you are not able to select some characters because the software you are using to display the rendered results does not have that Unicode defined in its fonts library. So it's treating that character as an object or an empty box(commonly called “tofu”). But the render engine that is turning your python code(or TeX file) into a PDF/SVG does understand that Unicode and that's why you can see that particular character. So much for understanding the source of the issue.
Solution: You may use another IDE/browser if you are using that platform to see the results. Chrome usually supports most Unicodes. Except for those that are defined very recently.
Moreover, Ψ (Psi) is a Greek letter. Check if your Operating System does have Greek letters installed in its fonts library. If it doesn't, go to The Unicode Consortium website and search "Display Problems" it will come up with a page explaining how to install a font depending on your OS or browser.

Matplotlib version of latex command "\ell" looking extra-slanted

I use latex in matplotlib by setting
plt.rcParams.update({'mathtext.fontset': 'stix'})
plt.rcParams.update({'font.family': 'STIXGeneral'})
I am using the letter $\ell$ very often in my research and there is a small detail bothering me. As you can see below, matplotlib renders the symbol with the little loop smaller and the letter more slanted. To me it almost looks like a vertically stretched $e$. I tried using the "\mathrm{\ell}" command instead but it did not change anything.
Is there any way I could get the symbol to look normal?
PS: it looks like stackoverflow is not detecting the math mode $ for some reason. If you know how to fix it (or if I am doing something wrong) please point it out or edit the question. Thanks!
The reason is the font you are using in matplotlib. With the following settings, for example, you get the same letter as in overleaf:
import matplotlib.pyplot as plt
import numpy as np
# Example data
t = np.arange(0.0, 10, 1)
s = np.arange(0.0, 10, 1)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.xlabel(r'$\ell$', fontsize=30)
plt.ylabel(r'$\ell$', fontsize=30)
plt.plot(t, s)
plt.show()
You get:
However, In Jupyterlab I could not reproduce. It used the overleaf fonts even with your settings.
This proved to be the simplest solution for me. Thanks the others for pointing out the font being the issue.
Rather than
plt.rcParams.update({'mathtext.fontset': 'stix'})
plt.rcParams.update({'font.family': 'STIXGeneral'})
I now write the first line as
plt.rcParams.update({'mathtext.fontset': 'cm'})
which works like charm. This is helpful if you are someone like me not using TeX but just the mathtext matplotlib built-in function.

Is there any problem with the OpenSlide.read_region function?

I am using the python API of openslide packages to read some ndpi file.When I use the read_region function, sometimes it return a odd image. What problems could have happend?
I have tried to read the full image, and it will be worked well. Therefore, I think there is no problem with the original file.
from openslide import OpenSlide
import cv2
import numpy as np
slide = OpenSlide('/Users/xiaoying/django/ndpi-rest-api/slide/read/21814102D-PAS - 2018-05-28 17.18.24.ndpi')
image = slide.read_region((1, 0),6, (780, 960))
image.save('image1.png')
The output is strange output
As the read_region documentation says, the x and y parameters are always in the coordinate space of level 0. For the behavior you want, you'll need to multiply those parameters by the downsample of the level you're reading.
This appears to be a version-realted bug, see also
https://github.com/openslide/openslide/issues/291#issuecomment-722935212
The problem seems to relate to libpixman verions 0.38.x . There is a Workaround section written by GunnarFarneback suggesting to load a different version first e.g.
export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libpixman-1.so.0.34.0
upadte easier solution is:
We are using Python 3.6.8+ and this did the trick for us: conda install pixman=0.36.0

Trying to save output of display(Math('f(x) = x + 2C')) to an image file using jupyter notebook

I have learned how to display symbolic math in jupyter notebook using the display, Math, & Latex packages.
An example would be: display(Math('some math eqn')), which would result in clearly formatted symbolic math within jupyter notebook.
Now I am interested in exporting the display to an image file so I can use it elsewhere.
I tried using the code below, but it returned a NoneType object:
Image(display(Math('f(x) = x + 2C')), embed=True, format=PNG)
How would I go about doing this please?
Update:
I tried executing display(Math("\dfrac{5x}{3}")) via a cmd prompt and got this: <IPython.core.display.Math object>. I'm wondering if there's a way to convert this object type to an image?

Latex with IPython (IPython) error

While trying to use LaTeX with IPython, I used the following code:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
from How to write LaTeX in IPython Notebook?.
But, I got the following error.
<IPython.core.display.Math at 0x269a030>
What does this error mean? When do I get it? How can I get rid of it?
That is not an error. Run it with ipython notebook and you will see your integral displayed.
It is not an error, it is the output representation. Simply run the code inside the IPython notebook:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))

Categories

Resources