-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathlatex.py
597 lines (501 loc) · 18.1 KB
/
latex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# -*- coding: utf-8 -*-
"""Lower-level formatter of Mathics objects as (AMS)LaTeX strings.
AMS LaTeX is LaTeX with addition mathematical symbols, which
we may make use of via the mathics-scanner tables.
LaTeX formatting is usually initiated in Mathics via TeXForm[].
TeXForm in WMA is slightly vague or misleading since the output is
typically LaTeX rather than Plain TeX. In Mathics, we also assume AMS
LaTeX or more specifically that we the additional AMS Mathematical
Symbols exist.
"""
import re
from mathics.builtin.box.graphics import GraphicsBox
from mathics.builtin.box.graphics3d import Graphics3DBox
from mathics.builtin.box.layout import (
FractionBox,
GridBox,
RowBox,
SqrtBox,
StyleBox,
SubscriptBox,
SubsuperscriptBox,
SuperscriptBox,
)
from mathics.builtin.colors.color_directives import RGBColor
from mathics.core.atoms import String
from mathics.core.exceptions import BoxConstructError
from mathics.core.formatter import (
add_conversion_fn,
lookup_method as lookup_conversion_method,
)
from mathics.core.symbols import SymbolTrue
from mathics.format.asy_fns import asy_color, asy_create_pens, asy_number
# mathics_scanner does not generates this table in a way that we can load it here.
# When it get fixed, we can use that table instead of this one:
amstex_operators = {
"\u2032": "'",
"\u2032\u2032": "''",
"\u2062": " ",
"\u221e": r"\infty ",
"\u00d7": r"\times ",
"(": r"\left(",
"[": r"\left[",
"{": r"\left\{",
")": r"\right)",
"]": r"\right]",
"}": r"\right\}",
"\u301a": r"\left[\left[",
"\u301b": r"\right]\right]",
",": ",",
", ": ", ",
"\u222b": r"\int",
"\u2146": r"\, d",
"\uF74C": r"\, d",
"\U0001D451": r"\, d",
"\u2211": r"\sum",
"\u220f": r"\prod",
}
TEX_REPLACE = {
"{": r"\{",
"}": r"\}",
"_": r"\_",
"$": r"\$",
"%": r"\%",
"#": r"\#",
"&": r"\&",
"\\": r"\backslash{}",
"^": r"{}^{\wedge}",
"~": r"\sim{}",
"|": r"\vert{}",
"\u222b": r"\int ",
"\u2146": r"\, d",
"\uF74C": r"\, d",
"\U0001D451": r"\, d",
}
TEX_TEXT_REPLACE = TEX_REPLACE.copy()
TEX_TEXT_REPLACE.update(
{
"<": r"$<$",
">": r"$>$",
"~": r"$\sim$",
"|": r"$\vert$",
"\\": r"$\backslash$",
"^": r"${}^{\wedge}$",
"\u222b": r"$\int$ ",
"\uF74C": r"\, d",
}
)
TEX_REPLACE_RE = re.compile("([" + "".join([re.escape(c) for c in TEX_REPLACE]) + "])")
def encode_tex(text: str, in_text=False) -> str:
def replace(match):
c = match.group(1)
repl = TEX_TEXT_REPLACE if in_text else TEX_REPLACE
# return TEX_REPLACE[c]
return repl.get(c, c)
text = TEX_REPLACE_RE.sub(replace, text)
text = text.replace("\n", "\\newline\n")
return text
def string(self, **options) -> str:
text = self.value
def render(format, string, in_text=False):
return format % encode_tex(string, in_text)
if text.startswith('"') and text.endswith('"'):
show_string_characters = (
options.get("System`ShowStringCharacters", None) is SymbolTrue
)
# In WMA, ``TeXForm`` never adds quotes to
# strings, even if ``InputForm`` or ``FullForm``
# is required, to so get the standard WMA behaviour,
# this option is set to False:
# show_string_characters = False
if show_string_characters:
return render(r"\text{``%s''}", text[1:-1], in_text=True)
else:
return render(r"\text{%s}", text[1:-1], in_text=True)
elif text and text[0] in "0123456789-.":
return render("%s", text)
else:
op_string = amstex_operators.get(text, None)
if op_string:
return op_string
elif len(text) > 1:
return render(r"\text{%s}", text, in_text=True)
else:
return render("%s", text)
add_conversion_fn(String, string)
def fractionbox(self, **options) -> str:
_options = self.box_options.copy()
_options.update(options)
options = _options
# This removes the auxiliar parentheses in
# numerator and denominator if they are not
# needed. See comment in `mathics.builtin.arithfns.basic.Divide`
def remove_trivial_parentheses(x):
if not isinstance(x, RowBox):
return x
elements = x.elements
if len(elements) != 3:
return x
left, center, right = elements
if not (isinstance(left, String) and isinstance(right, String)):
return x
open_p, close_p = elements[0].value, elements[-1].value
if open_p == "(" and close_p == ")":
return center
return x
num = remove_trivial_parentheses(self.num)
den = remove_trivial_parentheses(self.den)
return "\\frac{%s}{%s}" % (
lookup_conversion_method(num, "latex")(num, **options),
lookup_conversion_method(den, "latex")(den, **options),
)
add_conversion_fn(FractionBox, fractionbox)
def gridbox(self, elements=None, **box_options) -> str:
def boxes_to_tex(box, **options):
return lookup_conversion_method(box, "latex")(box, **options)
if not elements:
elements = self._elements
evaluation = box_options.get("evaluation")
items, options = self.get_array(elements, evaluation)
new_box_options = box_options.copy()
new_box_options["inside_list"] = True
column_alignments = options["System`ColumnAlignments"].get_name()
try:
column_alignments = {
"System`Center": "c",
"System`Left": "l",
"System`Right": "r",
}[column_alignments]
except KeyError:
# invalid column alignment
raise BoxConstructError
column_count = 1
for row in items:
if isinstance(row, tuple):
column_count = max(column_count, len(row))
result = r"\begin{array}{%s} " % (column_alignments * column_count)
for index, row in enumerate(items):
if isinstance(row, tuple):
result += " & ".join(boxes_to_tex(item, **new_box_options) for item in row)
else:
result += r"\multicolumn{%s}{%s}{%s}" % (
str(column_count),
column_alignments,
boxes_to_tex(row, **new_box_options),
)
if index != len(items) - 1:
result += "\\\\ "
result += r"\end{array}"
return result
add_conversion_fn(GridBox, gridbox)
def sqrtbox(self, **options):
_options = self.box_options.copy()
_options.update(options)
options = _options
if self.index:
return "\\sqrt[%s]{%s}" % (
lookup_conversion_method(self.radicand, "latex")(self.radicand, **options),
lookup_conversion_method(self.index, "latex")(self.index, **options),
)
return "\\sqrt{%s}" % lookup_conversion_method(self.radicand, "latex")(
self.radicand, **options
)
add_conversion_fn(SqrtBox, sqrtbox)
def superscriptbox(self, **options):
_options = self.box_options.copy()
_options.update(options)
options = _options
base_to_tex = lookup_conversion_method(self.base, "latex")
tex1 = base_to_tex(self.base, **options)
sup_string = self.superindex.get_string_value()
# Handle derivatives
if sup_string == "\u2032":
return "%s'" % tex1
elif sup_string == "\u2032\u2032":
return "%s''" % tex1
else:
base = self.tex_block(tex1, True)
superidx_to_tex = lookup_conversion_method(self.superindex, "latex")
superindx = self.tex_block(superidx_to_tex(self.superindex, **options), True)
if len(superindx) == 1 and isinstance(self.superindex, (String, StyleBox)):
return "%s^%s" % (
base,
superindx,
)
else:
return "%s^{%s}" % (
base,
superindx,
)
add_conversion_fn(SuperscriptBox, superscriptbox)
def subscriptbox(self, **options):
_options = self.box_options.copy()
_options.update(options)
options = _options
base_to_tex = lookup_conversion_method(self.base, "latex")
subidx_to_tex = lookup_conversion_method(self.subindex, "latex")
return "%s_%s" % (
self.tex_block(base_to_tex(self.base, **options), True),
self.tex_block(subidx_to_tex(self.subindex, **options)),
)
add_conversion_fn(SubscriptBox, subscriptbox)
def subsuperscriptbox(self, **options):
_options = self.box_options.copy()
_options.update(options)
options = _options
base_to_tex = lookup_conversion_method(self.base, "latex")
subidx_to_tex = lookup_conversion_method(self.subindex, "latex")
superidx_to_tex = lookup_conversion_method(self.superindex, "latex")
return "%s_%s^%s" % (
self.tex_block(base_to_tex(self.base, **options), True),
self.tex_block(subidx_to_tex(self.subindex, **options)),
self.tex_block(superidx_to_tex(self.superindex, **options)),
)
add_conversion_fn(SubsuperscriptBox, subsuperscriptbox)
def rowbox(self, **options) -> str:
_options = self.box_options.copy()
_options.update(options)
options = _options
return "".join(
[
lookup_conversion_method(element, "latex")(element, **options)
for element in self.items
]
)
add_conversion_fn(RowBox, rowbox)
def stylebox(self, **options) -> str:
_options = self.box_options.copy()
_options.update(options)
options = _options
return lookup_conversion_method(self.boxes, "latex")(self.boxes, **options)
add_conversion_fn(StyleBox, stylebox)
def graphicsbox(self, elements=None, **options) -> str:
"""This is the top-level function that converts a Mathics Expression
in to something suitable for AMSLaTeX.
However right now the only LaTeX support for graphics is via Asymptote and
that seems to be the package of choice in general for LaTeX.
"""
if not elements:
elements = self._elements
fields = self._prepare_elements(elements, options, max_width=450)
if len(fields) == 2:
elements, calc_dimensions = fields
else:
elements, calc_dimensions = fields[0], fields[-2]
fields = calc_dimensions()
if len(fields) == 8:
xmin, xmax, ymin, ymax, w, h, width, height = fields
elements.view_width = w
else:
assert len(fields) == 9
xmin, xmax, ymin, ymax, _, _, _, width, height = fields
elements.view_width = width
asy_completely_visible = "\n".join(
lookup_conversion_method(element, "asy")(element)
for element in elements.elements
if element.is_completely_visible
)
asy_regular = "\n".join(
lookup_conversion_method(element, "asy")(element)
for element in elements.elements
if not element.is_completely_visible
)
asy_box = "box((%s,%s), (%s,%s))" % (
asy_number(xmin),
asy_number(ymin),
asy_number(xmax),
asy_number(ymax),
)
if self.background_color is not None:
color, opacity = asy_color(self.background_color)
asy_background = "filldraw(%s, %s);" % (asy_box, color)
else:
asy_background = ""
tex = r"""
\begin{asy}
usepackage("amsmath");
size(%scm, %scm);
%s
%s
clip(%s);
%s
\end{asy}
""" % (
asy_number(width / 60),
asy_number(height / 60),
asy_background,
asy_regular,
asy_box,
asy_completely_visible,
)
return tex
add_conversion_fn(GraphicsBox, graphicsbox)
def graphics3dbox(self, elements=None, **options) -> str:
if not elements:
elements = self._elements
(
elements,
axes,
ticks,
ticks_style,
calc_dimensions,
boxscale,
) = self._prepare_elements(elements, options, max_width=450)
elements._apply_boxscaling(boxscale)
format_fn = lookup_conversion_method(elements, "asy")
if format_fn is not None:
asy = format_fn(elements)
else:
asy = elements.to_asy()
xmin, xmax, ymin, ymax, zmin, zmax, boxscale, w, h = calc_dimensions()
# TODO: Intelligently place the axes on the longest non-middle edge.
# See algorithm used by web graphics in mathics/web/media/graphics.js
# for details of this. (Projection to sceen etc).
# Choose axes placement (boundbox edge vertices)
axes_indices = []
if axes[0]:
axes_indices.append(0)
if axes[1]:
axes_indices.append(6)
if axes[2]:
axes_indices.append(8)
# Draw boundbox and axes
boundbox_asy = ""
boundbox_lines = self.get_boundbox_lines(xmin, xmax, ymin, ymax, zmin, zmax)
for i, line in enumerate(boundbox_lines):
if i in axes_indices:
pen = asy_create_pens(
edge_color=RGBColor(components=(0, 0, 0, 1)), stroke_width=1.5
)
else:
pen = asy_create_pens(
edge_color=RGBColor(components=(0.4, 0.4, 0.4, 1)), stroke_width=1
)
path = "--".join(["(%.5g,%.5g,%.5g)" % coords for coords in line])
boundbox_asy += "draw((%s), %s);\n" % (path, pen)
# TODO: Intelligently draw the axis ticks such that they are always
# directed inward and choose the coordinate direction which makes the
# ticks the longest. Again, details in mathics/web/media/graphics.js
# Draw axes ticks
ticklength = 0.05 * max([xmax - xmin, ymax - ymin, zmax - zmin])
pen = asy_create_pens(
edge_color=RGBColor(components=(0, 0, 0, 1)), stroke_width=1.2
)
for xi in axes_indices:
if xi < 4: # x axis
for i, tick in enumerate(ticks[0][0]):
line = [
(tick, boundbox_lines[xi][0][1], boundbox_lines[xi][0][2]),
(
tick,
boundbox_lines[xi][0][1],
boundbox_lines[xi][0][2] + ticklength,
),
]
path = "--".join(["({0},{1},{2})".format(*coords) for coords in line])
boundbox_asy += "draw(({0}), {1});\n".format(path, pen)
boundbox_asy += 'label("{0}",{1},{2});\n'.format(
ticks[0][2][i],
(tick, boundbox_lines[xi][0][1], boundbox_lines[xi][0][2]),
"S",
)
for small_tick in ticks[0][1]:
line = [
(
small_tick,
boundbox_lines[xi][0][1],
boundbox_lines[xi][0][2],
),
(
small_tick,
boundbox_lines[xi][0][1],
boundbox_lines[xi][0][2] + 0.5 * ticklength,
),
]
path = "--".join(["({0},{1},{2})".format(*coords) for coords in line])
boundbox_asy += "draw(({0}), {1});\n".format(path, pen)
if 4 <= xi < 8: # y axis
for i, tick in enumerate(ticks[1][0]):
line = [
(boundbox_lines[xi][0][0], tick, boundbox_lines[xi][0][2]),
(
boundbox_lines[xi][0][0],
tick,
boundbox_lines[xi][0][2] - ticklength,
),
]
path = "--".join(["({0},{1},{2})".format(*coords) for coords in line])
boundbox_asy += "draw(({0}), {1});\n".format(path, pen)
boundbox_asy += 'label("{0}",{1},{2});\n'.format(
ticks[1][2][i],
(boundbox_lines[xi][0][0], tick, boundbox_lines[xi][0][2]),
"NW",
)
for small_tick in ticks[1][1]:
line = [
(
boundbox_lines[xi][0][0],
small_tick,
boundbox_lines[xi][0][2],
),
(
boundbox_lines[xi][0][0],
small_tick,
boundbox_lines[xi][0][2] - 0.5 * ticklength,
),
]
path = "--".join(["({0},{1},{2})".format(*coords) for coords in line])
boundbox_asy += "draw(({0}), {1});\n".format(path, pen)
if 8 <= xi: # z axis
for i, tick in enumerate(ticks[2][0]):
line = [
(boundbox_lines[xi][0][0], boundbox_lines[xi][0][1], tick),
(
boundbox_lines[xi][0][0],
boundbox_lines[xi][0][1] + ticklength,
tick,
),
]
path = "--".join(["({0},{1},{2})".format(*coords) for coords in line])
boundbox_asy += "draw(({0}), {1});\n".format(path, pen)
boundbox_asy += 'label("{0}",{1},{2});\n'.format(
ticks[2][2][i],
(boundbox_lines[xi][0][0], boundbox_lines[xi][0][1], tick),
"W",
)
for small_tick in ticks[2][1]:
line = [
(
boundbox_lines[xi][0][0],
boundbox_lines[xi][0][1],
small_tick,
),
(
boundbox_lines[xi][0][0],
boundbox_lines[xi][0][1] + 0.5 * ticklength,
small_tick,
),
]
path = "--".join(["({0},{1},{2})".format(*coords) for coords in line])
boundbox_asy += "draw(({0}), {1});\n".format(path, pen)
(height, width) = (400, 400) # TODO: Proper size
tex = r"""
\begin{{asy}}
import three;
import solids;
size({0}cm, {1}cm);
currentprojection=perspective({2[0]},{2[1]},{2[2]});
currentlight=light(rgb(0.5,0.5,1), specular=red, (2,0,2), (2,2,2), (0,2,2));
{3}
{4}
\end{{asy}}
""".format(
asy_number(width / 60),
asy_number(height / 60),
# Rescale viewpoint
[vp * max([xmax - xmin, ymax - ymin, zmax - zmin]) for vp in self.viewpoint],
asy,
boundbox_asy,
)
return tex
add_conversion_fn(Graphics3DBox, graphics3dbox)