andrea andrea - 1 year ago 107
LaTeX Question

How to specify LaTeX output format in Astropy

I just started to use

to write tables in LaTeX format. It does the job, however, when I write down the table, the units normalized to large masses, typically 1e6 solar masses, are displayed without the scientific notation.

An example:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def table_write():
from astropy.io import ascii
import astropy.table
import astropy.units as u


#fake data, ~ the same order of magnitude of real ones
Mbh = [1e1, 7e3]
t_final = [13, 12.2]

tab = astropy.table.Table([Mbh, t_final],
names = ['Mbh', 't_final'])
tab['Mbh'].unit = '1e6 Msun'
tab['t_final'].unit = 'Gyr'

ascii.write(tab,
Writer=ascii.Latex,
latexdict=ascii.latex.latexdicts['AA'])


if __name__ == "__main__":
table_write()


The output is

\begin{table}
\begin{tabular}{cc}
\hline \hline
Mbh & t_final \\
$\mathrm{1000000\,M_{\odot}}$ & $\mathrm{Gyr}$ \\
\hline
10.0 & 13.0 \\
7000.0 & 12.2 \\
\hline
\end{tabular}
\end{table}


which is fine, except for


\mathrm{1000000\,M_{\odot}}


which should be a nice


\mathrm{10^{6}\,M_{\odot}}


So, I would like to format a part of the unit.
The documentation seems to report a way to do this, but it is absolutely not clear.

Answer Source

You could define a new unit u.Msun with the astropy.units.def_unit() method. If you want, you can also specify the column's format to scientific notation with the argument formats of the astropy.io.ascii.write() method,

from astropy.io import ascii
import astropy.table
import astropy.units as u

def table_write():

    #fake data, ~ the same order of magnitude of real ones
    Mbh = [1e1,  7e3]
    t_final = [13, 12.2]

    tab = astropy.table.Table([Mbh, t_final],
            names =  ['Mbh', 't_final'])

    # Define new unit with LaTeX format
    new_Msun = u.def_unit('1E6 Msun', 10**6*u.Msun, format={'latex': r'10^6\,M_{\odot}'})

    tab['Mbh'].unit = new_Msun
    tab['t_final'].unit = u.Gyr

    ascii.write(tab,
            Writer=ascii.Latex,
            latexdict=ascii.latex.latexdicts['AA'],
            formats={'Mbh':'%.0E'}) # Set the column's format to scientific notation


if __name__ == "__main__":
    table_write()

LaTeX:

\begin{table}
\begin{tabular}{cc}
\hline \hline
Mbh & t_final \\
$\mathrm{10^6\,M_{\odot}}$ & $\mathrm{Gyr}$ \\
\hline
1E+01 & 13.0 \\
7E+03 & 12.2 \\
\hline
\end{tabular}
\end{table}

As you can see here the new unit is actually 10^6 times the Sun mass, whereas the text formatting with LaTeX is right,

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download