2
2
Format Mathics objects
3
3
"""
4
4
5
- import random
6
5
import math
7
6
import networkx as nx
7
+ import random
8
+ from tempfile import NamedTemporaryFile
9
+
10
+ try :
11
+ import matplotlib .pyplot as plt
12
+ except ImportError :
13
+ plt = None
14
+
15
+ try :
16
+ import matplotlib .image as mpimg
17
+ except ImportError :
18
+ mpimg = None
19
+
20
+ try :
21
+ from cairosvg import svg2png
22
+ except ImportError :
23
+ svg2png = None
8
24
9
25
10
26
def format_output (obj , expr , format = None ):
27
+ def eval_boxes (result , fn , obj , ** options ):
28
+ try :
29
+ boxes = fn (evaluation = obj , ** options )
30
+ except BoxError :
31
+ boxes = None
32
+ if not hasattr (obj , "seen_box_error" ):
33
+ obj .seen_box_error = True
34
+ obj .message (
35
+ "General" , "notboxes" , Expression ("FullForm" , result ).evaluate (obj )
36
+ )
37
+
38
+ return boxes
39
+
11
40
if format is None :
12
41
format = obj .format
13
42
@@ -28,12 +57,20 @@ def format_output(obj, expr, format=None):
28
57
if len (leaves ) == 1 :
29
58
expr = leaves [0 ]
30
59
elif expr_type in ("System`Graphics" , "System`Plot" ):
31
- result = "-System Graphics-"
32
- result = Expression ("StandardForm" , expr )
33
- result = result .format (obj , "System`MathMLForm" )
34
- # ml_str = result.leaves[0].leaves[0]
35
- # FIXME: not quite right. Need to parse out strings
36
- # display_svg(str(ml_str))
60
+ form_expr = Expression ("StandardForm" , expr )
61
+ result = form_expr .format (obj , "System`StandardForm" )
62
+ svg_str = eval_boxes (result , result .boxes_to_svg , obj )
63
+ if plt :
64
+ temp_png = NamedTemporaryFile (
65
+ mode = "w+b" , suffix = ".png" , prefix = "mathicsscript-"
66
+ )
67
+ svg2png (bytestring = svg_str , write_to = temp_png .name )
68
+ plt .axes ().set_axis_off ()
69
+ img = mpimg .imread (temp_png )
70
+ plt .imshow (img )
71
+ plt .show ()
72
+ temp_png .close ()
73
+ return expr_type
37
74
38
75
if format == "text" :
39
76
result = expr .format (obj , "System`OutputForm" )
@@ -359,7 +396,6 @@ def format_graph(G):
359
396
Format a Graph
360
397
"""
361
398
# FIXME handle graphviz as well
362
- import matplotlib .pyplot as plt
363
399
364
400
global node_size
365
401
global cached_pair
0 commit comments