22Format Mathics objects
33"""
44
5- import random
65import math
76import 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
824
925
1026def 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+
1140 if format is None :
1241 format = obj .format
1342
@@ -28,12 +57,20 @@ def format_output(obj, expr, format=None):
2857 if len (leaves ) == 1 :
2958 expr = leaves [0 ]
3059 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
3774
3875 if format == "text" :
3976 result = expr .format (obj , "System`OutputForm" )
@@ -359,7 +396,6 @@ def format_graph(G):
359396 Format a Graph
360397 """
361398 # FIXME handle graphviz as well
362- import matplotlib .pyplot as plt
363399
364400 global node_size
365401 global cached_pair
0 commit comments