Skip to content

Commit a344b02

Browse files
committed
Add LaTex reader/writer for astropy.cosmology (issue astropy#14837)
1 parent 09795ab commit a344b02

3 files changed

Lines changed: 186 additions & 0 deletions

File tree

‎astropy/cosmology/__init__.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
from ._src.parameter import Parameter
2828
from .realizations import available, default_cosmology
2929

30+
from .latex import read_latex, write_latex, read_latex_from_string
31+
3032
__all__ = [ # noqa: RUF100, RUF022
3133
# Public Submodules
3234
"realizations",
@@ -66,6 +68,9 @@
6668
"Planck13",
6769
"Planck15",
6870
"Planck18",
71+
"read_latex",
72+
"write_latex",
73+
"read_latex_from_string",
6974
]
7075

7176

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import os
2+
import tempfile
3+
import pytest
4+
5+
from astropy.cosmology import FlatLambdaCDM
6+
from astropy.cosmology import read_latex, write_latex, read_latex_from_string
7+
8+
9+
def _create_temp_latex(content: str) -> str:
10+
11+
"""
12+
Helper Function: write the given LaTeX content to a temporary .tex file,
13+
the return the filename so tests can read from it.
14+
"""
15+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".tex", mode="w")
16+
tmp.write(content)
17+
tmp.close()
18+
return tmp.name
19+
20+
21+
def test_read_latex():
22+
# Create a minimal LaTeX document with H0 and Om0 parameters
23+
sample = (
24+
"\\documentclass{article}\n"
25+
"\\begin{document}\n"
26+
"H0 = 65.0\n"
27+
"Om0 = 0.25\n"
28+
"\\end{document}\n"
29+
)
30+
path = _create_temp_latex(sample)
31+
cosmo = read_latex(path)
32+
os.remove(path)
33+
34+
assert abs(cosmo.H0.value - 65.0) < 1e-8
35+
assert abs(cosmo.Om0 - 0.25) < 1e-8
36+
37+
38+
def test_write_and_read_roundtrip():
39+
# Start from a known FlatLambdaCDM instance
40+
original = FlatLambdaCDM(H0=68.0, Om0=0.32)
41+
tmpfile = tempfile.NamedTemporaryFile(delete=False, suffix=".tex")
42+
tmpfile.close()
43+
44+
# Write it out, then read it back in
45+
write_latex(original, tmpfile.name)
46+
loaded = read_latex(tmpfile.name)
47+
os.remove(tmpfile.name)
48+
49+
assert abs(loaded.H0.value - 68.0) < 1e-8
50+
assert abs(loaded.Om0 - 0.32) < 1e-8
51+
52+
53+
def test_read_latex_from_string_function():
54+
# Test the convenience function that parses a raw string
55+
latex_str = "H0 = 72.0\nOm0 = 0.28\n"
56+
cosmo = read_latex_from_string(latex_str)
57+
58+
assert abs(cosmo.H0.value - 72.0) < 1e-8
59+
assert abs(cosmo.Om0 - 0.28) < 1e-8
60+
61+
62+
if __name__ == "__main__":
63+
pytest.main(["-q", __file__])

‎astropy/cosmology/latex.py‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import re # regex operations
2+
import os # file removal
3+
import tempfile # creating temporary files
4+
from astropy.cosmology import FlatLambdaCDM # the cosmology class we build
5+
6+
def read_latex(file_path):
7+
# Open the .tex file and read all lines
8+
f = open(file_path, 'r')
9+
lines = f.readlines()
10+
f.close()
11+
12+
params = {} # store parsed parameters
13+
14+
# regex: (name) = (number)
15+
pattern = re.compile(r"([A-Za-z0-9_]+)\s*=\s*([0-9.+\-Ee]+)")
16+
for line in lines:
17+
m = pattern.search(line)
18+
if m:
19+
key = m.group(1) # parameter name
20+
val = float(m.group(2)) # numeric value
21+
params[key] = val
22+
23+
# default values if missing
24+
H0_val = params.get('H0', 70.0)
25+
Om0_val = params.get('Om0', 0.3)
26+
27+
# build and return a FlatLambdaCDM object
28+
cosm = FlatLambdaCDM(H0=H0_val, Om0=Om0_val)
29+
return cosm
30+
31+
def write_latex(cosmology, file_path):
32+
# prepare lines for a minimal .tex document
33+
lines = []
34+
h0 = cosmology.H0.value # extract H0
35+
om0 = cosmology.Om0 # extract Om0
36+
ow0 = 1.0 - om0 # compute Ode0
37+
38+
lines.append("\\documentclass{article}\n")
39+
lines.append("\\begin{document}\n")
40+
lines.append("\\section*{Cosmology Parameters}\n")
41+
lines.append(f"H0 = {h0:.2f}\n") # write H0
42+
lines.append(f"Om0 = {om0:.4f}\n") # write Om0
43+
lines.append(f"Ode0 = {ow0:.4f}\n") # write Ode0
44+
lines.append("\\end{document}\n")
45+
46+
# write to disk
47+
f = open(file_path, 'w')
48+
f.writelines(lines)
49+
f.close()
50+
51+
def _create_temp_latex(content):
52+
# helper: write raw string to a temp .tex file
53+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.tex', mode='w')
54+
tmp.write(content)
55+
tmp.close()
56+
return tmp.name
57+
58+
def test_read_latex():
59+
# make a small LaTeX document, read it, then assert values
60+
sample = (
61+
"\\documentclass{article}\n"
62+
"\\begin{document}\n"
63+
"H0 = 65.0\n"
64+
"Om0 = 0.25\n"
65+
"\\end{document}\n"
66+
)
67+
path = _create_temp_latex(sample)
68+
cosmo = read_latex(path)
69+
os.remove(path)
70+
assert abs(cosmo.H0.value - 65.0) < 1e-6
71+
assert abs(cosmo.Om0 - 0.25) < 1e-6
72+
73+
def test_write_and_read_roundtrip():
74+
# write a FlatLambdaCDM to .tex and read it back
75+
original = FlatLambdaCDM(H0=68.0, Om0=0.32)
76+
tmpfile = tempfile.NamedTemporaryFile(delete=False, suffix='.tex')
77+
tmpfile.close()
78+
79+
write_latex(original, tmpfile.name) # dump to file
80+
loaded = read_latex(tmpfile.name) # parse it back
81+
os.remove(tmpfile.name)
82+
83+
assert abs(loaded.H0.value - 68.0) < 1e-6
84+
assert abs(loaded.Om0 - 0.32) < 1e-6
85+
86+
def read_latex_from_string(latex_string):
87+
# convenience: parse a raw LaTeX string without manual files
88+
tmp_path = _create_temp_latex(latex_string)
89+
result = read_latex(tmp_path)
90+
os.remove(tmp_path)
91+
return result
92+
93+
def test_read_latex_from_string_function():
94+
# test the string‐based reader
95+
latex_str = "H0 = 72.0\nOm0 = 0.28\n"
96+
cosmo = read_latex_from_string(latex_str)
97+
assert abs(cosmo.H0.value - 72.0) < 1e-6
98+
assert abs(cosmo.Om0 - 0.28) < 1e-6
99+
100+
def example_usage():
101+
# example script you can run directly
102+
content = (
103+
"\\documentclass{article}\n"
104+
"\\begin{document}\n"
105+
"H0 = 75.0\n"
106+
"Om0 = 0.27\n"
107+
"Ode0 = 0.73\n"
108+
"\\end{document}\n"
109+
)
110+
temp_path = _create_temp_latex(content)
111+
cosmo = read_latex(temp_path)
112+
os.remove(temp_path)
113+
print("Loaded cosmology:")
114+
print(" H0 =", cosmo.H0.value)
115+
print(" Om0 =", cosmo.Om0)
116+
117+
if __name__ == "__main__":
118+
example_usage()

0 commit comments

Comments
 (0)