1

I'm looking for a way to render astropy variables inside LaTeX strings within an IPython notebook. For example, given a simple premise,

from astropy.constants import c
import astropy.units as u
from astropy import log

the speed of light is beautifully rendered by default as:

latex-rendering

by simply typing it in the ipython prompt. Now, what if I would like to embed this in a string? How to hop on the same rendering train already used by astropy to print an example string like 'Speed limit: {}'.format(c)?

Everything I've tried so far, including variations of LaTeX-formatted strings, only displays an ASCII string as an output: ascii-rendering

Vlas Sokolov
  • 3,733
  • 3
  • 26
  • 43
  • This is effectively a duplicate of http://stackoverflow.com/questions/13208286/how-to-write-latex-in-ipython-notebook See the accepted answer there. – Iguananaut Nov 21 '16 at 23:25
  • I disagree. The answer you linked explains how to use ipython display function to print latex code, and would not produce an acceptable output for, e.g., `display(Math('{}'.format(c)))`. This question asks specifically for how to expand latex functionality already present in the `astropy.units` module to a more general case. – Vlas Sokolov Nov 21 '16 at 23:41

2 Answers2

2

There is probably a more elegant solution, but this works: enter image description here

Tom Aldcroft
  • 2,339
  • 1
  • 14
  • 16
0
# Science
import numpy as np
from astropy.units import Unit

# Notebook
from IPython.display import Markdown
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

# Handy functions
def Qshow(Q, sigfig=2, unit=None, name=None):
    name = Q.info.name
    if unit is not None:
        Q = Q.to(unit)
    if sigfig is not None:
        q = Q.round(sigfig - int(np.log10(Q.value)))
    else:
        q = Q
    if name is not None:
        output = Markdown(f'{name} = {q._repr_latex_()}')
    else:
        output = Markdown(f'{q._repr_latex_()}')
    return output

# Parameter
density = 1.23456e12 * Unit('g/cm^3')
density.info.name = r'$\rho$'

# Results
Qshow(density)

enter image description here

See this gist for latest version.

Miladiouss
  • 4,270
  • 1
  • 27
  • 34