Skip to content

Commit cc94733

Browse files
committed
exceptions
1 parent a9b20a6 commit cc94733

File tree

1 file changed

+35
-25
lines changed

1 file changed

+35
-25
lines changed

generate/testdata.py

Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,15 @@
1-
import re
2-
31
import os.path as osp
42
import pickle
3+
import re
54
import subprocess
65
import tempfile
76
from typing import Dict, Optional, Union
87

98
import matplotlib
109
import matplotlib.pyplot as plt
11-
10+
from doc2rst import DOCTEST_RST_DATA_PCL
1211
from mathics import __version__, settings, version_info, version_string
13-
from mathics import settings
1412
from mathics.doc.utils import load_doctest_data
15-
from doc2rst import DOCTEST_RST_DATA_PCL
1613

1714
ASY_LATEX_BLOCK = re.compile(r"\\begin{asy}([\s\S]+?)\\end{asy}")
1815
IMAGE_LATEX_ENTRY = re.compile(r"(?m)\\includegraphics\[(.*?)\]{(.*?)}")
@@ -23,7 +20,6 @@
2320
SKIP_ASY = False
2421

2522

26-
2723
def convert_asy_code(content: str, key=""):
2824
"""Convert asy code into a png picture.
2925
Return a LaTeX includegraphics instruction"""
@@ -36,7 +32,9 @@ def convert_asy_code(content: str, key=""):
3632
tmp_path, _ = osp.split(tmp_filename)
3733
result = tmp_filename[:-4] + ".png"
3834
if not SKIP_ASY:
39-
subprocess.run(["asy", "-f", "png", "-render", "70", tmp_filename], cwd=tmp_path)
35+
subprocess.run(
36+
["asy", "-f", "png", "-render", "70", tmp_filename], cwd=tmp_path
37+
)
4038
result = osp.abspath(result)
4139
return r"\includegraphics[]{" + result + "}"
4240

@@ -46,7 +44,7 @@ def convert_latex_to_png(content, key=""):
4644
Generate a png image from LaTeX
4745
code.
4846
"""
49-
tmp_filename = get_tmp_filename(prefix="eq_"+key, suffix=".png")
47+
tmp_filename = get_tmp_filename(prefix="eq_" + key, suffix=".png")
5048
try:
5149
latex_to_img(f"${content}$", tmp_filename)
5250
except ValueError as e:
@@ -57,7 +55,7 @@ def convert_latex_to_png(content, key=""):
5755

5856

5957
def convert_mathics_latex_to_RsT(
60-
out_latex: Optional[Union[str, dict]], key=""
58+
out_latex: Optional[Union[str, dict]], key=""
6159
) -> Optional[Union[str, dict]]:
6260
"""
6361
Convert a LaTeX block into a RsT compatible
@@ -74,7 +72,9 @@ def convert_mathics_latex_to_RsT(
7472
assert isinstance(out_latex, str)
7573
# out_latex is a string
7674
out_latex = str(out_latex).strip()
77-
out_latex = ASY_LATEX_BLOCK.sub(lambda m: convert_asy_code(m.group(1), key), out_latex)
75+
out_latex = ASY_LATEX_BLOCK.sub(
76+
lambda m: convert_asy_code(m.group(1), key), out_latex
77+
)
7878
out_latex = out_latex.strip()
7979
img_match = IMAGE_LATEX_ENTRY.fullmatch(out_latex)
8080
if img_match:
@@ -94,7 +94,6 @@ def convert_mathics_latex_to_RsT(
9494
return f":math:`{out_latex}`\n"
9595

9696

97-
9897
def convert_output_to_rst(test_data, key=""):
9998
"""
10099
Convert the output data from a doctest
@@ -104,9 +103,11 @@ def convert_output_to_rst(test_data, key=""):
104103
try:
105104
converted_data = {
106105
"query": test_data["query"],
107-
"results": [convert_result_to_rst(item, key) for item in test_data["results"]],
106+
"results": [
107+
convert_result_to_rst(item, key) for item in test_data["results"]
108+
],
108109
}
109-
except ValueError, RuntimeError:
110+
except (ValueError, RuntimeError):
110111
print("Result from ", test_data["query"], "could not be converted.")
111112
return None
112113
return converted_data
@@ -120,7 +121,10 @@ def convert_result_to_rst(result_dict, key=""):
120121
converted_result = {
121122
"line": result_dict["line"],
122123
"form": "RsT",
123-
"out": [convert_mathics_latex_to_RsT(out_line, key) for out_line in result_dict["out"]],
124+
"out": [
125+
convert_mathics_latex_to_RsT(out_line, key)
126+
for out_line in result_dict["out"]
127+
],
124128
"result": convert_mathics_latex_to_RsT(result_dict["result"], key),
125129
}
126130
for key in result_dict:
@@ -136,11 +140,12 @@ def convert_test_data_to_rst(latex_test_data):
136140
"""
137141
rst_tex_data = {}
138142
for key, test in latex_test_data.items():
139-
rst_tex_data[key] = convert_output_to_rst(test, ("_".join(key[:-1])).replace(" ", "_")+"_")
143+
rst_tex_data[key] = convert_output_to_rst(
144+
test, ("_".join(key[:-1])).replace(" ", "_") + "_"
145+
)
140146
return rst_tex_data
141147

142148

143-
144149
def get_tmp_filename(prefix="", suffix=""):
145150
# This produces a random name, where the png file is going to be stored.
146151
# LaTeX does not have a native way to store an figure embedded in
@@ -158,23 +163,31 @@ def latex_to_img(tex, fn):
158163
https://stackoverflow.com/questions/1381741/converting-latex-code-to-images-or-other-displayble-format-with-python
159164
"""
160165
matplotlib.rcParams["text.latex.preamble"] = (
161-
"\\usepackage{multicol}\n" "\\usepackage{amsmath}\n" "\\usepackage{amssymb}\n" "\\usepackage{graphicx}\n"
166+
"\\usepackage{multicol}\n"
167+
"\\usepackage{amsmath}\n"
168+
"\\usepackage{amssymb}\n"
169+
"\\usepackage{graphicx}\n"
162170
)
163171
# LaTeX from matplotlib does not accept linebreaks or
164172
# the \text command. Use \mbox instead.
165-
tex = tex.replace(r'\text{',r'\mbox{')
173+
tex = tex.replace(r"\text{", r"\mbox{")
166174
tex = tex.replace("\n", " ")
167175
# TODO: adjust the size of the figure.
168-
plt.figure(figsize=(3,1))
176+
plt.figure(figsize=(3, 1))
169177
plt.rc("text", usetex=True)
170178
plt.rc("font", family="serif")
171179
plt.axis("off")
172180
plt.text(0.05, 0.5, f"{tex}", size=12)
173-
plt.savefig(fn, format="png", bbox_inches='tight', backend="pgf", dpi=250,)
181+
plt.savefig(
182+
fn,
183+
format="png",
184+
bbox_inches="tight",
185+
backend="pgf",
186+
dpi=250,
187+
)
174188
plt.close()
175189

176190

177-
178191
def read_doctest_data(quiet=False) -> Optional[Dict[tuple, dict]]:
179192
"""
180193
Read doctest information from PCL file and return this.
@@ -193,7 +206,6 @@ def read_doctest_data(quiet=False) -> Optional[Dict[tuple, dict]]:
193206
return {}
194207

195208

196-
197209
def main():
198210
"""Generate a pickle file with outputs compatible with RsT"""
199211
latex_test_data = read_doctest_data()
@@ -203,7 +215,5 @@ def main():
203215
print("done.")
204216

205217

206-
207-
208-
if __name__ == "__main__":
218+
if __name__ == "__main__":
209219
main()

0 commit comments

Comments
 (0)