Built-in Cosmology To/From Formats#

To see the a list of the available conversion formats:

>>> from astropy.cosmology import Cosmology
>>> Cosmology.to_format.list_formats()
      Format      Read Write Auto-identify
----------------- ---- ----- -------------
astropy.cosmology  Yes   Yes           Yes
    astropy.model  Yes   Yes           Yes
      astropy.row  Yes   Yes           Yes
    astropy.table  Yes   Yes           Yes
          mapping  Yes   Yes           Yes
             yaml  Yes   Yes            No

Cosmology#

Cosmology I/O, using to_format() and from_format().

This module provides functions to transform a Cosmology object to and from another Cosmology object. The functions are registered with convert_registry under the format name “astropy.cosmology”. You probably won’t need to use these functions as they are present mainly for completeness and testing.

>>> from astropy.cosmology import Cosmology, Planck18
>>> Planck18.to_format("astropy.cosmology") is Planck18
True
>>> Cosmology.from_format(Planck18) is Planck18
True

Mapping#

Cosmology <-> Mapping I/O, using to_format() and from_format().

This module provides functions to transform a Cosmology instance to a mapping (dict-like) object and vice versa, from a mapping object back to a Cosmology instance. The functions are registered with convert_registry under the format name “mapping”. The mapping object is a dict-like object, with the cosmology’s parameters and metadata as items. dict is a fundamental data structure in Python, and this representation of a Cosmology is useful for translating between many serialization and storage formats, or even passing arguments to functions.

We start with the simple case of outputting a Cosmology as a mapping.

>>> from astropy.cosmology import Cosmology, Planck18
>>> cm = Planck18.to_format('mapping')
>>> cm
{'cosmology': <class 'astropy.cosmology...FlatLambdaCDM'>,
 'name': 'Planck18', 'H0': <Quantity 67.66 km / (Mpc s)>, 'Om0': 0.30966,
 'Tcmb0': <Quantity 2.7255 K>, 'Neff': 3.046,
 'm_nu': <Quantity [0. , 0. , 0.06] eV>, 'Ob0': 0.04897,
 'meta': ...

cm is a dict, with the cosmology’s parameters and metadata as items.

How might we use this dict? One use is to unpack the dict into a function:

>>> def function(H0, Tcmb0, **kwargs): ...
>>> function(**cm)

Another use is to merge the dict with another dict:

>>> cm2 = {'H0': 70, 'Tcmb0': 2.7}
>>> cm | cm2
{'cosmology': <class 'astropy.cosmology...FlatLambdaCDM'>, ..., 'H0': 70, ...}

Most saliently, the dict can also be used to construct a new cosmological instance identical to the Planck 2018 cosmology from which it was generated.

>>> cosmo = Cosmology.from_format(cm, format="mapping")
>>> cosmo
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
              Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

How did from_format() know to return an instance of the FlatLambdaCDM class? The mapping object has a field cosmology which can be either the string name of the cosmology class (e.g. “FlatLambdaCDM”) or the class itself.

This field can be omitted under two conditions.

  1. If the cosmology class is passed as the cosmology keyword argument to from_format(),

  2. If a specific cosmology class, e.g. FlatLambdaCDM, is used to parse the data.

To the first point, we can pass the cosmology class as the cosmology keyword argument to from_format().

>>> del cm["cosmology"]  # remove cosmology class
>>> Cosmology.from_format(cm, cosmology="FlatLambdaCDM")
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
              Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

To the second point, we can use specific cosmology class to parse the data.

>>> from astropy.cosmology import FlatLambdaCDM
>>> FlatLambdaCDM.from_format(cm)
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
              Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

Also, the class’ default parameter values are used to fill in any information missing in the data. For example, if Tcmb0 is missing, the default value of 0.0 K is used.

>>> del cm["Tcmb0"]  # show FlatLambdaCDM provides default
>>> FlatLambdaCDM.from_format(cm)
FlatLambdaCDM(name="Planck18", H0=..., Tcmb0=0.0 K, ...)

If instead of missing information, there is extra information, there are a few options. The first is to use the move_to_meta keyword argument to move fields that are not in the Cosmology constructor to the Cosmology’s metadata.

>>> cm2 = cm | {"extra": 42, "cosmology": "FlatLambdaCDM"}
>>> cosmo = Cosmology.from_format(cm2, move_to_meta=True)
>>> cosmo.meta
OrderedDict([('extra', 42), ...])

Alternatively, the rename keyword argument can be used to rename keys in the mapping to fields of the Cosmology. This is crucial when the mapping has keys that are not valid arguments to the Cosmology constructor.

>>> cm3 = dict(cm)  # copy
>>> cm3["cosmo_cls"] = "FlatLambdaCDM"
>>> cm3["cosmo_name"] = cm3.pop("name")
>>> rename = {'cosmo_cls': 'cosmology', 'cosmo_name': 'name'}
>>> Cosmology.from_format(cm3, rename=rename)
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
                Tcmb0=0.0 K, Neff=3.046, m_nu=None, Ob0=0.04897)

Let’s take a closer look at to_format(), because there a lot of options, to tailor the output to specific needs.

The dictionary type may be changed with the cls keyword argument:

>>> from collections import OrderedDict
>>> Planck18.to_format('mapping', cls=OrderedDict)
OrderedDict([('cosmology', <class 'astropy.cosmology...FlatLambdaCDM'>),
    ('name', 'Planck18'), ('H0', <Quantity 67.66 km / (Mpc s)>),
    ('Om0', 0.30966), ('Tcmb0', <Quantity 2.7255 K>), ('Neff', 3.046),
    ('m_nu', <Quantity [0.  , 0.  , 0.06] eV>), ('Ob0', 0.04897),
    ('meta', ...

Sometimes it is more useful to have the name of the cosmology class, not the type itself. The keyword argument cosmology_as_str may be used:

>>> Planck18.to_format('mapping', cosmology_as_str=True)
{'cosmology': 'FlatLambdaCDM', ...

The metadata is normally included as a nested mapping. To move the metadata into the main mapping, use the keyword argument move_from_meta. This kwarg inverts move_to_meta in Cosmology.to_format("mapping", move_to_meta=...) where extra items are moved to the metadata (if the cosmology constructor does not have a variable keyword-only argument – **kwargs).

>>> from astropy.cosmology import Planck18
>>> Planck18.to_format('mapping', move_from_meta=True)
{'cosmology': <class 'astropy.cosmology...FlatLambdaCDM'>,
    'name': 'Planck18', 'Oc0': 0.2607, 'n': 0.9665, 'sigma8': 0.8102, ...

Lastly, the keys in the mapping may be renamed with the rename keyword.

>>> rename = {'cosmology': 'cosmo_cls', 'name': 'cosmo_name'}
>>> Planck18.to_format('mapping', rename=rename)
{'cosmo_cls': <class 'astropy.cosmology...FlatLambdaCDM'>,
 'cosmo_name': 'Planck18', ...

Table#

Cosmology <-> Table I/O, using to_format() and from_format().

This module provides functions to transform a Cosmology object to and from a Table object. The functions are registered with convert_registry under the format name “astropy.table”. Table itself has an abundance of I/O methods, making this conversion useful for further interoperability with other formats.

A Cosmology as a QTable will have the cosmology’s name and parameters as columns.

>>> from astropy.cosmology import Planck18
>>> ct = Planck18.to_format("astropy.table")
>>> ct
<QTable length=1>
    name        H0        Om0    Tcmb0    Neff      m_nu      Ob0
            km / (Mpc s)            K                 eV
    str8     float64    float64 float64 float64  float64[3] float64
-------- ------------ ------- ------- ------- ----------- -------
Planck18        67.66 0.30966  2.7255   3.046 0.0 .. 0.06 0.04897

The cosmological class and other metadata, e.g. a paper reference, are in the Table’s metadata.

>>> ct.meta
OrderedDict([..., ('cosmology', 'FlatLambdaCDM')])

Cosmology supports the astropy Table-like protocol (see Table-like Objects) to the same effect:

>>> from astropy.table import QTable
>>> QTable(Planck18)
<QTable length=1>
  name        H0        Om0    Tcmb0    Neff      m_nu      Ob0
         km / (Mpc s)            K                 eV
  str8     float64    float64 float64 float64  float64[3] float64
-------- ------------ ------- ------- ------- ----------- -------
Planck18        67.66 0.30966  2.7255   3.046 0.0 .. 0.06 0.04897

To move the cosmology class from the metadata to a Table row, set the cosmology_in_meta argument to False:

>>> Planck18.to_format("astropy.table", cosmology_in_meta=False)
<QTable length=1>
    cosmology     name        H0        Om0    Tcmb0    Neff      m_nu      Ob0
                        km / (Mpc s)            K                 eV
    str13       str8     float64    float64 float64 float64  float64[3] float64
------------- -------- ------------ ------- ------- ------- ----------- -------
FlatLambdaCDM Planck18        67.66 0.30966  2.7255   3.046 0.0 .. 0.06 0.04897

Astropy recommends QTable for tables with Quantity columns. However the returned type may be overridden using the cls argument:

>>> from astropy.table import Table
>>> Planck18.to_format("astropy.table", cls=Table)
<Table length=1>
...

Fields of the cosmology may be renamed using the rename argument.

>>> Planck18.to_format("astropy.table", rename={"H0": "Hubble"})
<QTable length=1>
    name      Hubble      Om0    Tcmb0    Neff      m_nu      Ob0
            km / (Mpc s)            K                 eV
    str8     float64    float64 float64 float64  float64[3] float64
-------- ------------ ------- ------- ------- ----------- -------
Planck18        67.66 0.30966  2.7255   3.046 0.0 .. 0.06 0.04897

Appropriately formatted tables can be converted to Cosmology instances. Since the Table can hold arbitrary metadata, we can faithfully round-trip a Cosmology through Table, e.g. to construct a Planck18 cosmology identical to the instance from which it was generated.

>>> ct = Planck18.to_format("astropy.table")
>>> cosmo = Cosmology.from_format(ct, format="astropy.table")
>>> cosmo
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
                Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)
>>> cosmo == Planck18
True

The cosmology information (row or metadata) may be omitted if the cosmology class (or its string name) is passed as the cosmology keyword argument to from_format().

>>> del ct.meta["cosmology"]  # remove cosmology from metadata
>>> Cosmology.from_format(ct, cosmology="FlatLambdaCDM")
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
                Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

Alternatively, specific cosmology classes can be used to parse the data.

>>> from astropy.cosmology import FlatLambdaCDM
>>> FlatLambdaCDM.from_format(ct)
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
                Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

When using a specific cosmology class, the class’ default parameter values are used to fill in any missing information.

>>> del ct["Tcmb0"]  # show FlatLambdaCDM provides default
>>> FlatLambdaCDM.from_format(ct)
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
                Tcmb0=0.0 K, Neff=3.046, m_nu=None, Ob0=0.04897)

For tables with multiple rows of cosmological parameters, the index argument is needed to select the correct row. The index can be an integer for the row number or, if the table is indexed by a column, the value of that column. If the table is not indexed and index is a string, the “name” column is used as the indexing column.

Here is an example where index is needed and can be either an integer (for the row number) or the name of one of the cosmologies, e.g. ‘Planck15’.

>>> from astropy.cosmology import Planck13, Planck15, Planck18
>>> from astropy.table import vstack
>>> cts = vstack([c.to_format("astropy.table")
...               for c in (Planck13, Planck15, Planck18)],
...              metadata_conflicts='silent')
>>> cts
<QTable length=3>
    name        H0        Om0    Tcmb0    Neff      m_nu      Ob0
            km / (Mpc s)            K                 eV
    str8     float64    float64 float64 float64  float64[3]  float64
-------- ------------ ------- ------- ------- ----------- --------
Planck13        67.77 0.30712  2.7255   3.046 0.0 .. 0.06 0.048252
Planck15        67.74  0.3075  2.7255   3.046 0.0 .. 0.06   0.0486
Planck18        67.66 0.30966  2.7255   3.046 0.0 .. 0.06  0.04897
>>> cosmo = Cosmology.from_format(cts, index=1, format="astropy.table")
>>> cosmo == Planck15
True

Fields in the table can be renamed to match the Cosmology class’ signature using the rename argument. This is useful when the table’s column names do not match the class’ parameter names.

>>> renamed_table = Planck18.to_format("astropy.table", rename={"H0": "Hubble"})
>>> renamed_table
<QTable length=1>
    name      Hubble      Om0    Tcmb0    Neff      m_nu      Ob0
            km / (Mpc s)            K                 eV
    str8     float64    float64 float64 float64  float64[3] float64
-------- ------------ ------- ------- ------- ----------- -------
Planck18        67.66 0.30966  2.7255   3.046 0.0 .. 0.06 0.04897
>>> cosmo = Cosmology.from_format(renamed_table, format="astropy.table",
...                               rename={"Hubble": "H0"})
>>> cosmo == Planck18
True

Model#

Cosmology <-> Model I/O, using to_format() and from_format().

This module provides functions to transform a Cosmology object to and from a Model. The functions are registered with convert_registry under the format name “astropy.model”.

Using format="astropy.model" any redshift(s) method of a cosmology may be turned into a astropy.modeling.Model. Each Cosmology Parameter is converted to a astropy.modeling.Model Parameter and the redshift-method to the model’s __call__ / evaluate. Now you can fit cosmologies with data!

>>> from astropy.cosmology import Cosmology, Planck18
>>> model = Planck18.to_format("astropy.model", method="lookback_time")
>>> model
<FlatLambdaCDMCosmologyLookbackTimeModel(H0=67.66 km / (Mpc s), Om0=0.30966,
    Tcmb0=2.7255 K, Neff=3.046, m_nu=[0.  , 0.  , 0.06] eV, Ob0=0.04897,
    name='Planck18')>

The Planck 2018 cosmology can be recovered with from_format().

>>> print(Cosmology.from_format(model))
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
              Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

YAML#

Cosmology <-> YAML I/O, using to_format() and from_format().

This module provides functions to transform a Cosmology object to and from a yaml representation. The functions are registered with convert_registry under the format name “yaml”. This format is primarily intended for use by other I/O functions, e.g. Table’s metadata serialization, which themselves require YAML serialization.

>>> from astropy.cosmology import Planck18
>>> yml = Planck18.to_format("yaml")
>>> yml  
"!astropy.cosmology...FlatLambdaCDM\nH0: !astropy.units.Quantity...
>>> print(Cosmology.from_format(yml, format="yaml"))
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
              Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

Row#

Cosmology <-> Row I/O, using to_format() and from_format().

A Cosmology as a Row will have the cosmology’s name and parameters as columns.

>>> from astropy.cosmology import Planck18
>>> cr = Planck18.to_format("astropy.row")
>>> cr
<Row index=0>
    cosmology     name        H0        Om0    Tcmb0    Neff      m_nu      Ob0
                        km / (Mpc s)            K                 eV
    str13       str8     float64    float64 float64 float64  float64[3] float64
------------- -------- ------------ ------- ------- ------- ----------- -------
FlatLambdaCDM Planck18        67.66 0.30966  2.7255   3.046 0.0 .. 0.06 0.04897

The cosmological class and other metadata, e.g. a paper reference, are in the Table’s metadata.

>>> cr.meta
OrderedDict([('Oc0', 0.2607), ('n', 0.9665), ...])

Now this row can be used to load a new cosmological instance identical to the Planck18 cosmology from which it was generated.

>>> cosmo = Cosmology.from_format(cr, format="astropy.row")
>>> cosmo
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
                Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

For more information on the argument options, see Table.

Built-in Cosmology Read/Write Formats#

To see a list of the available read/write file formats:

>>> from astropy.cosmology import Cosmology
>>> Cosmology.write.list_formats()
   Format   Read Write Auto-identify
----------- ---- ----- -------------
 ascii.ecsv  Yes   Yes           Yes
 ascii.html  Yes   Yes           Yes
ascii.latex   No   Yes           Yes

ECSV#

Cosmology <-> ECSV I/O, using read() and write().

This module provides functions to write/read a Cosmology object to/from an ECSV file. The functions are registered with readwrite_registry under the format name “ascii.ecsv”.

We assume the following setup:

>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> temp_dir = TemporaryDirectory()

To see reading a Cosmology from an ECSV file, we first write a Cosmology to an ECSV file:

>>> from astropy.cosmology import Cosmology, Planck18
>>> file = Path(temp_dir.name) / "file.ecsv"
>>> Planck18.write(file)
>>> with open(file) as f: print(f.read())
# %ECSV 1.0
# ---
# datatype:
# - {name: name, datatype: string}
# - {name: H0, unit: km / (Mpc s), datatype: float64, description: Hubble ...}
...
# meta: !!omap
# - {Oc0: 0.2607}
...
# schema: astropy-2.0
name H0 Om0 Tcmb0 Neff m_nu Ob0
Planck18 67.66 0.30966 2.7255 3.046 [0.0,0.0,0.06] 0.04897

Now we can read the Cosmology from the ECSV file, constructing a new cosmological instance identical to the Planck18 cosmology from which it was generated.

>>> cosmo = Cosmology.read(file)
>>> print(cosmo)
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
            Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)
>>> cosmo == Planck18
True

If a file already exists, attempting to write will raise an error unless overwrite=True.

>>> Planck18.write(file, overwrite=True)

By default the cosmology class is written to the Table metadata. This can be changed to a column of the table using the cosmology_in_meta keyword argument.

>>> file = Path(temp_dir.name) / "file2.ecsv"
>>> Planck18.write(file, cosmology_in_meta=False)
>>> with open(file) as f: print(f.read())
# %ECSV 1.0
# ---
# datatype:
# - {name: cosmology, datatype: string}
# - {name: name, datatype: string}
...
# meta: !!omap
# - {Oc0: 0.2607}
...
# schema: astropy-2.0
cosmology name H0 Om0 Tcmb0 Neff m_nu Ob0
FlatLambdaCDM Planck18 67.66 0.30966 2.7255 3.046 [0.0,0.0,0.06] 0.04897

The cosmology information (column or metadata) may be omitted if the cosmology class (or its string name) is passed as the cosmology keyword argument to read(). Alternatively, specific cosmology classes can be used to parse the data.

>>> from astropy.cosmology import FlatLambdaCDM
>>> print(FlatLambdaCDM.read(file))
FlatLambdaCDM(name="Planck18", H0=67.66 km / (Mpc s), Om0=0.30966,
                Tcmb0=2.7255 K, Neff=3.046, m_nu=[0. 0. 0.06] eV, Ob0=0.04897)

When using a specific cosmology class, the class’ default parameter values are used to fill in any missing information.

For files with multiple rows of cosmological parameters, the index argument is needed to select the correct row. The index can be an integer for the row number or, if the table is indexed by a column, the value of that column. If the table is not indexed and index is a string, the “name” column is used as the indexing column.

Here is an example where index is needed and can be either an integer (for the row number) or the name of one of the cosmologies, e.g. ‘Planck15’.

>>> from astropy.cosmology import Planck13, Planck15, Planck18
>>> from astropy.table import vstack
>>> cts = vstack([c.to_format("astropy.table")
...               for c in (Planck13, Planck15, Planck18)],
...              metadata_conflicts='silent')
>>> file = Path(temp_dir.name) / "file3.ecsv"
>>> cts.write(file)
>>> with open(file) as f: print(f.read())
# %ECSV 1.0
# ---
# datatype:
# - {name: name, datatype: string}
...
# meta: !!omap
# - {Oc0: 0.2607}
...
# schema: astropy-2.0
name H0 Om0 Tcmb0 Neff m_nu Ob0
Planck13 67.77 0.30712 2.7255 3.046 [0.0,0.0,0.06] 0.048252
Planck15 67.74 0.3075 2.7255 3.046 [0.0,0.0,0.06] 0.0486
Planck18 67.66 0.30966 2.7255 3.046 [0.0,0.0,0.06] 0.04897
>>> cosmo = Cosmology.read(file, index="Planck15", format="ascii.ecsv")
>>> cosmo == Planck15
True

Fields of the table in the file can be renamed to match the Cosmology class’ signature using the rename argument. This is useful when the files’s column names do not match the class’ parameter names.

>>> file = Path(temp_dir.name) / "file4.ecsv"
>>> Planck18.write(file, rename={"H0": "Hubble"})
>>> with open(file) as f: print(f.read())
# %ECSV 1.0
# ---
# datatype:
# - {name: name, datatype: string}
...
# meta: !!omap
# - {Oc0: 0.2607}
...
# schema: astropy-2.0
name Hubble Om0 Tcmb0 Neff m_nu Ob0
Planck18 67.66 0.30966 2.7255 3.046 [0.0,0.0,0.06] 0.04897
>>> cosmo = Cosmology.read(file, rename={"Hubble": "H0"})
>>> cosmo == Planck18
True

By default Cosmology instances are written using QTable as an intermediate representation (for details see to_format(), with format="astropy.table"). The Table type can be changed using the cls keyword argument.

>>> from astropy.table import Table
>>> file = Path(temp_dir.name) / "file5.ecsv"
>>> Planck18.write(file, cls=Table)

For most use cases, the default cls of QTable is recommended and will be largely indistinguishable from other table types, as the ECSV format is agnostic to the table type. An example of a difference that might necessitate using a different table type is if a different ECSV schema is desired.

Additional keyword arguments are passed to QTable.read and QTable.write.

LaTeX#

Cosmology <-> LaTeX I/O, using read() and write().

We assume the following setup:

>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> temp_dir = TemporaryDirectory()

Writing a cosmology to a LaTeX file will produce a table with the cosmology’s type, name, and parameters as columns.

>>> from astropy.cosmology import Cosmology, Planck18
>>> file = Path(temp_dir.name) / "file.tex"
>>> Planck18.write(file, format="ascii.latex")
>>> with open(file) as f: print(f.read())
\begin{table}
\begin{tabular}{cccccccc}
cosmology & name & $H_0$ & $\Omega_{m,0}$ & $T_{0}$ & $N_{eff}$ & $m_{nu}$ & $\Omega_{b,0}$ \\
&  & $\mathrm{km\,Mpc^{-1}\,s^{-1}}$ &  & $\mathrm{K}$ &  & $\mathrm{eV}$ &  \\
FlatLambdaCDM & Planck18 & 67.66 & 0.30966 & 2.7255 & 3.046 & 0.0 .. 0.06 & 0.04897 \\
\end{tabular}
\end{table}

The cosmology’s metadata is not included in the table.

To save the cosmology in an existing file, use overwrite=True; otherwise, an error will be raised.

>>> Planck18.write(file, format="ascii.latex", overwrite=True)

To use a different table class as the underlying writer, use the cls kwarg. For more information on the available table classes, see the documentation on Astropy’s table classes and on Cosmology.to_format("astropy.table").

By default the parameter names are converted to LaTeX format. To disable this, set latex_names=False.

>>> file = Path(temp_dir.name) / "file2.tex"
>>> Planck18.write(file, format="ascii.latex", latex_names=False)
>>> with open(file) as f: print(f.read())
\begin{table}
\begin{tabular}{cccccccc}
cosmology & name & H0 & Om0 & Tcmb0 & Neff & m_nu & Ob0 \\
&  & $\mathrm{km\,Mpc^{-1}\,s^{-1}}$ &  & $\mathrm{K}$ &  & $\mathrm{eV}$ &  \\
FlatLambdaCDM & Planck18 & 67.66 & 0.30966 & 2.7255 & 3.046 & 0.0 .. 0.06 & 0.04897 \\
\end{tabular}
\end{table}

HTML#

Cosmology <-> html I/O, using read() and write().

We assume the following setup:

>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> temp_dir = TemporaryDirectory()

Writing a cosmology to a html file will produce a table with the cosmology’s type, name, and parameters as columns.

>>> from astropy.cosmology import Planck18
>>> file = Path(temp_dir.name) / "file.html"
>>> Planck18.write(file)
>>> with open(file) as f: print(f.read())
<html>
<head>
<meta charset="utf-8"/>
<meta content="text/html;charset=UTF-8" http-equiv="Content-type"/>
</head>
<body>
<table>
<thead>
<tr>
    <th>cosmology</th> <th>name</th> <th>H0</th> <th>Om0</th> <th>Tcmb0</th>
    <th>Neff</th> <th colspan="3">m_nu</th> <th>Ob0</th>
</tr>
</thead>
<tr>
    <td>FlatLambdaCDM</td> <td>Planck18</td> <td>67.66</td> <td>0.30966</td>
    <td>2.7255</td> <td>3.046</td> <td>0.0</td> <td>0.0</td> <td>0.06</td>
    <td>0.04897</td>
</tr>
</table>
</body>
</html>

The cosmology’s metadata is not included in the file.

To save the cosmology in an existing file, use overwrite=True; otherwise, an error will be raised.

>>> Planck18.write(file, overwrite=True)

To use a different table class as the underlying writer, use the cls kwarg. For more information on the available table classes, see the documentation on Astropy’s table classes and on Cosmology.to_format("astropy.table").

By default the parameter names are not converted to LaTeX / MathJax format. To enable this, set latex_names=True.

>>> file = Path(temp_dir.name) / "file2.html"
>>> Planck18.write(file, latex_names=True)
>>> with open(file) as f: print(f.read())
<html>
...
<thead>
    <tr>
    <th>cosmology</th>
    <th>name</th>
    <th>$$H_{0}$$</th>
    <th>$$\Omega_{m,0}$$</th>
    <th>$$T_{0}$$</th>
    <th>$$N_{eff}$$</th>
    <th colspan="3">$$m_{nu}$$</th>
    <th>$$\Omega_{b,0}$$</th>
    </tr>
...

Note

A HTML file containing a Cosmology HTML table should have scripts enabling MathJax.

<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script type="text/javascript" id="MathJax-script" async
    src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>