|
| 1 | +import astropy.units as u |
1 | 2 | from astropy.cosmology.connect import readwrite_registry |
2 | 3 | from astropy.cosmology.core import Cosmology |
3 | 4 | from astropy.table import QTable |
@@ -50,14 +51,26 @@ def read_mrt(filename, index=None, *, move_to_meta=False, cosmology=None, **kwar |
50 | 51 | # Reading is handled by `QTable`. |
51 | 52 | table = QTable.read(filename, format="ascii.mrt", **kwargs) |
52 | 53 |
|
53 | | - # Create a single column named 'm_nu' by combining the values from the 'mnu0', 'mnu1', and 'mnu2' columns |
| 54 | + # Create a single column named 'm_nu' by combining the values from the 'm_nu_i' columns |
54 | 55 | m_nu_data = [] |
55 | | - for i in ("mnu0", "mnu1", "mnu2"): |
56 | | - column_data = table[i][0] |
57 | | - m_nu_data.append(column_data.value) |
58 | | - table.remove_column(i) |
59 | | - |
60 | | - table.add_column([m_nu_data], name="m_nu", index=-2) |
| 56 | + i, more_m_nu = 0, True |
| 57 | + while more_m_nu: |
| 58 | + cn = f"m_nu[{i}]" # column name |
| 59 | + if cn not in table.colnames: |
| 60 | + more_m_nu = False |
| 61 | + continue |
| 62 | + |
| 63 | + m_nu_data.append(table[cn][0]) |
| 64 | + table.remove_column(cn) |
| 65 | + |
| 66 | + i += 1 # increment the m_nu index |
| 67 | + |
| 68 | + col = ( |
| 69 | + [m_nu_data] |
| 70 | + if not isinstance(m_nu_data[0], u.Quantity) |
| 71 | + else [u.Quantity(m_nu_data)] |
| 72 | + ) |
| 73 | + table.add_column(col, name="m_nu", index=-2) |
61 | 74 |
|
62 | 75 | # Build the cosmology from table, using the private backend. |
63 | 76 | return from_table( |
@@ -97,13 +110,12 @@ def write_mrt(cosmology, file, *, overwrite=False, cls=QTable, **kwargs): |
97 | 110 | table_main = to_table(cosmology, cls=cls, cosmology_in_meta=False) |
98 | 111 | table = represent_mixins_as_columns(table_main) |
99 | 112 |
|
100 | | - # Replace the m_nu column with three columns with names 'mnu0', 'mnu1', 'mnu2' |
101 | | - m_nu = table_main["m_nu"] |
102 | | - table.remove_column("m_nu") |
103 | | - for i in range(len(m_nu[0])): |
104 | | - column_name = f"mnu{i}" |
105 | | - column_data = m_nu[0][i] |
106 | | - table.add_column(column_data, name=column_name, index=-2) |
| 113 | + # Replace the m_nu column with three columns with names 'm_nu_[i]' |
| 114 | + if "m_nu" in table.colnames: |
| 115 | + m_nu = table_main["m_nu"] |
| 116 | + table.remove_column("m_nu") |
| 117 | + cols, names = tuple(zip(*((m, f"m_nu[{i}]") for i, m in enumerate(m_nu[0])))) |
| 118 | + table.add_columns(cols, names=names, indexes=(-2, -2, -2)) |
107 | 119 |
|
108 | 120 | table.write(file, overwrite=overwrite, format="ascii.mrt", **kwargs) |
109 | 121 |
|
|
0 commit comments