如何在 Astropy 中指定 LaTeX 输出格式

How to specify LaTeX output format in Astropy

我刚开始用Astropy写LaTeX格式的tables。它完成了工作,但是,当我写下 table 时,标准化为大质量(通常为 1e6 个太阳质量)的单位显示时没有科学记数法。

一个例子:

#!/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()

输出为

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

很好,除了

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

应该不错

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

所以,我想格式化单元的一部分。 documentation 似乎报告了一种执行此操作的方法,但绝对不清楚。

您可以使用 astropy.units.def_unit() 方法定义一个 新单元 u.Msun。如果需要,您还可以使用 astropy.io.ascii.write() 方法的参数 formats 列的格式 指定为科学记数法,

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}

正如您在这里看到的,新单位实际上是太阳质量的 10^6 倍,而 LaTeX 的文本格式是正确的,