Skip to content

Commit 2550247

Browse files
committed
any number of m_nu cols
Signed-off-by: Nathaniel Starkman <[email protected]>
1 parent 8680796 commit 2550247

1 file changed

Lines changed: 26 additions & 14 deletions

File tree

‎astropy/cosmology/io/mrt.py‎

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import astropy.units as u
12
from astropy.cosmology.connect import readwrite_registry
23
from astropy.cosmology.core import Cosmology
34
from astropy.table import QTable
@@ -50,14 +51,26 @@ def read_mrt(filename, index=None, *, move_to_meta=False, cosmology=None, **kwar
5051
# Reading is handled by `QTable`.
5152
table = QTable.read(filename, format="ascii.mrt", **kwargs)
5253

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
5455
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)
6174

6275
# Build the cosmology from table, using the private backend.
6376
return from_table(
@@ -97,13 +110,12 @@ def write_mrt(cosmology, file, *, overwrite=False, cls=QTable, **kwargs):
97110
table_main = to_table(cosmology, cls=cls, cosmology_in_meta=False)
98111
table = represent_mixins_as_columns(table_main)
99112

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))
107119

108120
table.write(file, overwrite=overwrite, format="ascii.mrt", **kwargs)
109121

0 commit comments

Comments
 (0)