##// END OF EJS Templates
protect flush_figures post-exec function from user error...
MinRK -
Show More
@@ -1,180 +1,199 b''
1 1 """Produce SVG versions of active plots for display by the rich Qt frontend.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Imports
5 5 #-----------------------------------------------------------------------------
6 6 from __future__ import print_function
7 7
8 8 # Standard library imports
9 9 import sys
10 10
11 11 # Third-party imports
12 12 import matplotlib
13 13 from matplotlib.backends.backend_agg import new_figure_manager
14 14 from matplotlib._pylab_helpers import Gcf
15 15
16 16 # Local imports.
17 17 from IPython.config.configurable import SingletonConfigurable
18 18 from IPython.core.displaypub import publish_display_data
19 19 from IPython.core.pylabtools import print_figure, select_figure_format
20 20 from IPython.utils.traitlets import Dict, Instance, CaselessStrEnum, CBool
21 21 from IPython.utils.warn import warn
22 22
23 23 #-----------------------------------------------------------------------------
24 24 # Configurable for inline backend options
25 25 #-----------------------------------------------------------------------------
26 26 # inherit from InlineBackendConfig for deprecation purposes
27 27 class InlineBackendConfig(SingletonConfigurable):
28 28 pass
29 29
30 30 class InlineBackend(InlineBackendConfig):
31 31 """An object to store configuration of the inline backend."""
32 32
33 33 def _config_changed(self, name, old, new):
34 34 # warn on change of renamed config section
35 35 if new.InlineBackendConfig != old.InlineBackendConfig:
36 36 warn("InlineBackendConfig has been renamed to InlineBackend")
37 37 super(InlineBackend, self)._config_changed(name, old, new)
38 38
39 39 # The typical default figure size is too large for inline use,
40 40 # so we shrink the figure size to 6x4, and tweak fonts to
41 41 # make that fit.
42 42 rc = Dict({'figure.figsize': (6.0,4.0),
43 43 # 12pt labels get cutoff on 6x4 logplots, so use 10pt.
44 44 'font.size': 10,
45 45 # 72 dpi matches SVG/qtconsole
46 46 # this only affects PNG export, as SVG has no dpi setting
47 47 'savefig.dpi': 72,
48 48 # 10pt still needs a little more room on the xlabel:
49 49 'figure.subplot.bottom' : .125
50 50 }, config=True,
51 51 help="""Subset of matplotlib rcParams that should be different for the
52 52 inline backend."""
53 53 )
54 54
55 55 figure_format = CaselessStrEnum(['svg', 'png'], default_value='png', config=True,
56 56 help="The image format for figures with the inline backend.")
57 57
58 58 def _figure_format_changed(self, name, old, new):
59 59 if self.shell is None:
60 60 return
61 61 else:
62 62 select_figure_format(self.shell, new)
63 63
64 64 close_figures = CBool(True, config=True,
65 65 help="""Close all figures at the end of each cell.
66 66
67 67 When True, ensures that each cell starts with no active figures, but it
68 68 also means that one must keep track of references in order to edit or
69 69 redraw figures in subsequent cells. This mode is ideal for the notebook,
70 70 where residual plots from other cells might be surprising.
71 71
72 72 When False, one must call figure() to create new figures. This means
73 73 that gcf() and getfigs() can reference figures created in other cells,
74 74 and the active figure can continue to be edited with pylab/pyplot
75 75 methods that reference the current active figure. This mode facilitates
76 76 iterative editing of figures, and behaves most consistently with
77 77 other matplotlib backends, but figure barriers between cells must
78 78 be explicit.
79 79 """)
80 80
81 81 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
82 82
83 83
84 84 #-----------------------------------------------------------------------------
85 85 # Functions
86 86 #-----------------------------------------------------------------------------
87 87
88 88 def show(close=None):
89 89 """Show all figures as SVG/PNG payloads sent to the IPython clients.
90 90
91 91 Parameters
92 92 ----------
93 93 close : bool, optional
94 94 If true, a ``plt.close('all')`` call is automatically issued after
95 95 sending all the figures. If this is set, the figures will entirely
96 96 removed from the internal list of figures.
97 97 """
98 98 if close is None:
99 99 close = InlineBackend.instance().close_figures
100 100 try:
101 101 for figure_manager in Gcf.get_all_fig_managers():
102 102 send_figure(figure_manager.canvas.figure)
103 103 finally:
104 104 show._to_draw = []
105 105 if close:
106 106 matplotlib.pyplot.close('all')
107 107
108 108
109 109
110 110 # This flag will be reset by draw_if_interactive when called
111 111 show._draw_called = False
112 112 # list of figures to draw when flush_figures is called
113 113 show._to_draw = []
114 114
115 115
116 116 def draw_if_interactive():
117 117 """
118 118 Is called after every pylab drawing command
119 119 """
120 120 # signal that the current active figure should be sent at the end of execution.
121 121 # Also sets the _draw_called flag, signaling that there will be something to send.
122 122 # At the end of the code execution, a separate call to flush_figures()
123 123 # will act upon these values
124 124
125 125 fig = Gcf.get_active().canvas.figure
126 126
127 127 # ensure current figure will be drawn, and each subsequent call
128 128 # of draw_if_interactive() moves the active figure to ensure it is
129 129 # drawn last
130 130 try:
131 131 show._to_draw.remove(fig)
132 132 except ValueError:
133 133 # ensure it only appears in the draw list once
134 134 pass
135 135 show._to_draw.append(fig)
136 136 show._draw_called = True
137 137
138 138 def flush_figures():
139 139 """Send all figures that changed
140 140
141 141 This is meant to be called automatically and will call show() if, during
142 142 prior code execution, there had been any calls to draw_if_interactive.
143
144 This function is meant to be used as a post_execute callback in IPython,
145 so user-caused errors are handled with showtraceback() instead of being
146 allowed to raise. If this function is not called from within IPython,
147 then these exceptions will raise.
143 148 """
144 149 if not show._draw_called:
145 150 return
146 151
147 152 if InlineBackend.instance().close_figures:
148 153 # ignore the tracking, just draw and close all figures
149 return show(True)
150
154 try:
155 return show(True)
156 except Exception as e:
157 # safely show traceback if in IPython, else raise
158 try:
159 get_ipython().showtraceback()
160 return
161 except NameError:
162 raise e
151 163 try:
152 164 # exclude any figures that were closed:
153 165 active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()])
154 166 for fig in [ fig for fig in show._to_draw if fig in active ]:
155 send_figure(fig)
167 try:
168 send_figure(fig)
169 except Exception as e:
170 # safely show traceback if in IPython, else raise
171 try:
172 get_ipython().showtraceback()
173 break
174 except NameError:
175 raise e
156 176 finally:
157 177 # clear flags for next round
158 178 show._to_draw = []
159 179 show._draw_called = False
160 180
161 181
162 182 def send_figure(fig):
163 183 """Draw the current figure and send it as a PNG payload.
164 184 """
165 # For an empty figure, don't even bother calling figure_to_svg, to avoid
166 # big blank spaces in the qt console
167 if not fig.axes:
168 return
169 185 fmt = InlineBackend.instance().figure_format
170 186 data = print_figure(fig, fmt)
187 # print_figure will return None if there's nothing to draw:
188 if data is None:
189 return
171 190 mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' }
172 191 mime = mimetypes[fmt]
173 192 # flush text streams before sending figures, helps a little with output
174 193 # synchronization in the console (though it's a bandaid, not a real sln)
175 194 sys.stdout.flush(); sys.stderr.flush()
176 195 publish_display_data(
177 196 'IPython.zmq.pylab.backend_inline.send_figure',
178 197 {mime : data}
179 198 )
180 199
General Comments 0
You need to be logged in to leave comments. Login now