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