Show More
@@ -1,719 +1,736 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Top-level display functions for displaying object in different formats. |
|
2 | """Top-level display functions for displaying object in different formats. | |
3 |
|
3 | |||
4 | Authors: |
|
4 | Authors: | |
5 |
|
5 | |||
6 | * Brian Granger |
|
6 | * Brian Granger | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Copyright (C) 2013 The IPython Development Team |
|
10 | # Copyright (C) 2013 The IPython Development Team | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Imports |
|
17 | # Imports | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 |
|
19 | |||
20 | from __future__ import print_function |
|
20 | from __future__ import print_function | |
21 |
|
21 | |||
22 | import os |
|
22 | import os | |
23 | import struct |
|
23 | import struct | |
24 |
|
24 | |||
25 | from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, |
|
25 | from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode, | |
26 | unicode_type) |
|
26 | unicode_type) | |
27 |
|
27 | |||
28 | from .displaypub import publish_display_data |
|
28 | from .displaypub import publish_display_data | |
29 |
|
29 | |||
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 | # utility functions |
|
31 | # utility functions | |
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 |
|
33 | |||
34 | def _safe_exists(path): |
|
34 | def _safe_exists(path): | |
35 | """Check path, but don't let exceptions raise""" |
|
35 | """Check path, but don't let exceptions raise""" | |
36 | try: |
|
36 | try: | |
37 | return os.path.exists(path) |
|
37 | return os.path.exists(path) | |
38 | except Exception: |
|
38 | except Exception: | |
39 | return False |
|
39 | return False | |
40 |
|
40 | |||
41 | def _merge(d1, d2): |
|
41 | def _merge(d1, d2): | |
42 | """Like update, but merges sub-dicts instead of clobbering at the top level. |
|
42 | """Like update, but merges sub-dicts instead of clobbering at the top level. | |
43 |
|
43 | |||
44 | Updates d1 in-place |
|
44 | Updates d1 in-place | |
45 | """ |
|
45 | """ | |
46 |
|
46 | |||
47 | if not isinstance(d2, dict) or not isinstance(d1, dict): |
|
47 | if not isinstance(d2, dict) or not isinstance(d1, dict): | |
48 | return d2 |
|
48 | return d2 | |
49 | for key, value in d2.items(): |
|
49 | for key, value in d2.items(): | |
50 | d1[key] = _merge(d1.get(key), value) |
|
50 | d1[key] = _merge(d1.get(key), value) | |
51 | return d1 |
|
51 | return d1 | |
52 |
|
52 | |||
53 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): |
|
53 | def _display_mimetype(mimetype, objs, raw=False, metadata=None): | |
54 | """internal implementation of all display_foo methods |
|
54 | """internal implementation of all display_foo methods | |
55 |
|
55 | |||
56 | Parameters |
|
56 | Parameters | |
57 | ---------- |
|
57 | ---------- | |
58 | mimetype : str |
|
58 | mimetype : str | |
59 | The mimetype to be published (e.g. 'image/png') |
|
59 | The mimetype to be published (e.g. 'image/png') | |
60 | objs : tuple of objects |
|
60 | objs : tuple of objects | |
61 | The Python objects to display, or if raw=True raw text data to |
|
61 | The Python objects to display, or if raw=True raw text data to | |
62 | display. |
|
62 | display. | |
63 | raw : bool |
|
63 | raw : bool | |
64 | Are the data objects raw data or Python objects that need to be |
|
64 | Are the data objects raw data or Python objects that need to be | |
65 | formatted before display? [default: False] |
|
65 | formatted before display? [default: False] | |
66 | metadata : dict (optional) |
|
66 | metadata : dict (optional) | |
67 | Metadata to be associated with the specific mimetype output. |
|
67 | Metadata to be associated with the specific mimetype output. | |
68 | """ |
|
68 | """ | |
69 | if metadata: |
|
69 | if metadata: | |
70 | metadata = {mimetype: metadata} |
|
70 | metadata = {mimetype: metadata} | |
71 | if raw: |
|
71 | if raw: | |
72 | # turn list of pngdata into list of { 'image/png': pngdata } |
|
72 | # turn list of pngdata into list of { 'image/png': pngdata } | |
73 | objs = [ {mimetype: obj} for obj in objs ] |
|
73 | objs = [ {mimetype: obj} for obj in objs ] | |
74 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) |
|
74 | display(*objs, raw=raw, metadata=metadata, include=[mimetype]) | |
75 |
|
75 | |||
76 | #----------------------------------------------------------------------------- |
|
76 | #----------------------------------------------------------------------------- | |
77 | # Main functions |
|
77 | # Main functions | |
78 | #----------------------------------------------------------------------------- |
|
78 | #----------------------------------------------------------------------------- | |
79 |
|
79 | |||
80 | def display(*objs, **kwargs): |
|
80 | def display(*objs, **kwargs): | |
81 | """Display a Python object in all frontends. |
|
81 | """Display a Python object in all frontends. | |
82 |
|
82 | |||
83 | By default all representations will be computed and sent to the frontends. |
|
83 | By default all representations will be computed and sent to the frontends. | |
84 | Frontends can decide which representation is used and how. |
|
84 | Frontends can decide which representation is used and how. | |
85 |
|
85 | |||
86 | Parameters |
|
86 | Parameters | |
87 | ---------- |
|
87 | ---------- | |
88 | objs : tuple of objects |
|
88 | objs : tuple of objects | |
89 | The Python objects to display. |
|
89 | The Python objects to display. | |
90 | raw : bool, optional |
|
90 | raw : bool, optional | |
91 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, |
|
91 | Are the objects to be displayed already mimetype-keyed dicts of raw display data, | |
92 | or Python objects that need to be formatted before display? [default: False] |
|
92 | or Python objects that need to be formatted before display? [default: False] | |
93 | include : list or tuple, optional |
|
93 | include : list or tuple, optional | |
94 | A list of format type strings (MIME types) to include in the |
|
94 | A list of format type strings (MIME types) to include in the | |
95 | format data dict. If this is set *only* the format types included |
|
95 | format data dict. If this is set *only* the format types included | |
96 | in this list will be computed. |
|
96 | in this list will be computed. | |
97 | exclude : list or tuple, optional |
|
97 | exclude : list or tuple, optional | |
98 | A list of format type strings (MIME types) to exclude in the format |
|
98 | A list of format type strings (MIME types) to exclude in the format | |
99 | data dict. If this is set all format types will be computed, |
|
99 | data dict. If this is set all format types will be computed, | |
100 | except for those included in this argument. |
|
100 | except for those included in this argument. | |
101 | metadata : dict, optional |
|
101 | metadata : dict, optional | |
102 | A dictionary of metadata to associate with the output. |
|
102 | A dictionary of metadata to associate with the output. | |
103 | mime-type keys in this dictionary will be associated with the individual |
|
103 | mime-type keys in this dictionary will be associated with the individual | |
104 | representation formats, if they exist. |
|
104 | representation formats, if they exist. | |
105 | """ |
|
105 | """ | |
106 | raw = kwargs.get('raw', False) |
|
106 | raw = kwargs.get('raw', False) | |
107 | include = kwargs.get('include') |
|
107 | include = kwargs.get('include') | |
108 | exclude = kwargs.get('exclude') |
|
108 | exclude = kwargs.get('exclude') | |
109 | metadata = kwargs.get('metadata') |
|
109 | metadata = kwargs.get('metadata') | |
110 |
|
110 | |||
111 | from IPython.core.interactiveshell import InteractiveShell |
|
111 | from IPython.core.interactiveshell import InteractiveShell | |
112 |
|
112 | |||
113 | if not raw: |
|
113 | if not raw: | |
114 | format = InteractiveShell.instance().display_formatter.format |
|
114 | format = InteractiveShell.instance().display_formatter.format | |
115 |
|
115 | |||
116 | for obj in objs: |
|
116 | for obj in objs: | |
117 |
|
117 | |||
118 | # If _ipython_display_ is defined, use that to display this object. |
|
118 | # If _ipython_display_ is defined, use that to display this object. | |
119 | display_method = getattr(obj, '_ipython_display_', None) |
|
119 | display_method = getattr(obj, '_ipython_display_', None) | |
120 | if display_method is not None: |
|
120 | if display_method is not None: | |
121 | try: |
|
121 | try: | |
122 | display_method(**kwargs) |
|
122 | display_method(**kwargs) | |
123 | except NotImplementedError: |
|
123 | except NotImplementedError: | |
124 | pass |
|
124 | pass | |
125 | else: |
|
125 | else: | |
126 | continue |
|
126 | continue | |
127 | if raw: |
|
127 | if raw: | |
128 | publish_display_data('display', obj, metadata) |
|
128 | publish_display_data('display', obj, metadata) | |
129 | else: |
|
129 | else: | |
130 | format_dict, md_dict = format(obj, include=include, exclude=exclude) |
|
130 | format_dict, md_dict = format(obj, include=include, exclude=exclude) | |
131 | if metadata: |
|
131 | if metadata: | |
132 | # kwarg-specified metadata gets precedence |
|
132 | # kwarg-specified metadata gets precedence | |
133 | _merge(md_dict, metadata) |
|
133 | _merge(md_dict, metadata) | |
134 | publish_display_data('display', format_dict, md_dict) |
|
134 | publish_display_data('display', format_dict, md_dict) | |
135 |
|
135 | |||
136 |
|
136 | |||
137 | def display_pretty(*objs, **kwargs): |
|
137 | def display_pretty(*objs, **kwargs): | |
138 | """Display the pretty (default) representation of an object. |
|
138 | """Display the pretty (default) representation of an object. | |
139 |
|
139 | |||
140 | Parameters |
|
140 | Parameters | |
141 | ---------- |
|
141 | ---------- | |
142 | objs : tuple of objects |
|
142 | objs : tuple of objects | |
143 | The Python objects to display, or if raw=True raw text data to |
|
143 | The Python objects to display, or if raw=True raw text data to | |
144 | display. |
|
144 | display. | |
145 | raw : bool |
|
145 | raw : bool | |
146 | Are the data objects raw data or Python objects that need to be |
|
146 | Are the data objects raw data or Python objects that need to be | |
147 | formatted before display? [default: False] |
|
147 | formatted before display? [default: False] | |
148 | metadata : dict (optional) |
|
148 | metadata : dict (optional) | |
149 | Metadata to be associated with the specific mimetype output. |
|
149 | Metadata to be associated with the specific mimetype output. | |
150 | """ |
|
150 | """ | |
151 | _display_mimetype('text/plain', objs, **kwargs) |
|
151 | _display_mimetype('text/plain', objs, **kwargs) | |
152 |
|
152 | |||
153 |
|
153 | |||
154 | def display_html(*objs, **kwargs): |
|
154 | def display_html(*objs, **kwargs): | |
155 | """Display the HTML representation of an object. |
|
155 | """Display the HTML representation of an object. | |
156 |
|
156 | |||
157 | Parameters |
|
157 | Parameters | |
158 | ---------- |
|
158 | ---------- | |
159 | objs : tuple of objects |
|
159 | objs : tuple of objects | |
160 | The Python objects to display, or if raw=True raw HTML data to |
|
160 | The Python objects to display, or if raw=True raw HTML data to | |
161 | display. |
|
161 | display. | |
162 | raw : bool |
|
162 | raw : bool | |
163 | Are the data objects raw data or Python objects that need to be |
|
163 | Are the data objects raw data or Python objects that need to be | |
164 | formatted before display? [default: False] |
|
164 | formatted before display? [default: False] | |
165 | metadata : dict (optional) |
|
165 | metadata : dict (optional) | |
166 | Metadata to be associated with the specific mimetype output. |
|
166 | Metadata to be associated with the specific mimetype output. | |
167 | """ |
|
167 | """ | |
168 | _display_mimetype('text/html', objs, **kwargs) |
|
168 | _display_mimetype('text/html', objs, **kwargs) | |
169 |
|
169 | |||
170 |
|
170 | |||
171 | def display_svg(*objs, **kwargs): |
|
171 | def display_svg(*objs, **kwargs): | |
172 | """Display the SVG representation of an object. |
|
172 | """Display the SVG representation of an object. | |
173 |
|
173 | |||
174 | Parameters |
|
174 | Parameters | |
175 | ---------- |
|
175 | ---------- | |
176 | objs : tuple of objects |
|
176 | objs : tuple of objects | |
177 | The Python objects to display, or if raw=True raw svg data to |
|
177 | The Python objects to display, or if raw=True raw svg data to | |
178 | display. |
|
178 | display. | |
179 | raw : bool |
|
179 | raw : bool | |
180 | Are the data objects raw data or Python objects that need to be |
|
180 | Are the data objects raw data or Python objects that need to be | |
181 | formatted before display? [default: False] |
|
181 | formatted before display? [default: False] | |
182 | metadata : dict (optional) |
|
182 | metadata : dict (optional) | |
183 | Metadata to be associated with the specific mimetype output. |
|
183 | Metadata to be associated with the specific mimetype output. | |
184 | """ |
|
184 | """ | |
185 | _display_mimetype('image/svg+xml', objs, **kwargs) |
|
185 | _display_mimetype('image/svg+xml', objs, **kwargs) | |
186 |
|
186 | |||
187 |
|
187 | |||
188 | def display_png(*objs, **kwargs): |
|
188 | def display_png(*objs, **kwargs): | |
189 | """Display the PNG representation of an object. |
|
189 | """Display the PNG representation of an object. | |
190 |
|
190 | |||
191 | Parameters |
|
191 | Parameters | |
192 | ---------- |
|
192 | ---------- | |
193 | objs : tuple of objects |
|
193 | objs : tuple of objects | |
194 | The Python objects to display, or if raw=True raw png data to |
|
194 | The Python objects to display, or if raw=True raw png data to | |
195 | display. |
|
195 | display. | |
196 | raw : bool |
|
196 | raw : bool | |
197 | Are the data objects raw data or Python objects that need to be |
|
197 | Are the data objects raw data or Python objects that need to be | |
198 | formatted before display? [default: False] |
|
198 | formatted before display? [default: False] | |
199 | metadata : dict (optional) |
|
199 | metadata : dict (optional) | |
200 | Metadata to be associated with the specific mimetype output. |
|
200 | Metadata to be associated with the specific mimetype output. | |
201 | """ |
|
201 | """ | |
202 | _display_mimetype('image/png', objs, **kwargs) |
|
202 | _display_mimetype('image/png', objs, **kwargs) | |
203 |
|
203 | |||
204 |
|
204 | |||
205 | def display_jpeg(*objs, **kwargs): |
|
205 | def display_jpeg(*objs, **kwargs): | |
206 | """Display the JPEG representation of an object. |
|
206 | """Display the JPEG representation of an object. | |
207 |
|
207 | |||
208 | Parameters |
|
208 | Parameters | |
209 | ---------- |
|
209 | ---------- | |
210 | objs : tuple of objects |
|
210 | objs : tuple of objects | |
211 | The Python objects to display, or if raw=True raw JPEG data to |
|
211 | The Python objects to display, or if raw=True raw JPEG data to | |
212 | display. |
|
212 | display. | |
213 | raw : bool |
|
213 | raw : bool | |
214 | Are the data objects raw data or Python objects that need to be |
|
214 | Are the data objects raw data or Python objects that need to be | |
215 | formatted before display? [default: False] |
|
215 | formatted before display? [default: False] | |
216 | metadata : dict (optional) |
|
216 | metadata : dict (optional) | |
217 | Metadata to be associated with the specific mimetype output. |
|
217 | Metadata to be associated with the specific mimetype output. | |
218 | """ |
|
218 | """ | |
219 | _display_mimetype('image/jpeg', objs, **kwargs) |
|
219 | _display_mimetype('image/jpeg', objs, **kwargs) | |
220 |
|
220 | |||
221 |
|
221 | |||
222 | def display_latex(*objs, **kwargs): |
|
222 | def display_latex(*objs, **kwargs): | |
223 | """Display the LaTeX representation of an object. |
|
223 | """Display the LaTeX representation of an object. | |
224 |
|
224 | |||
225 | Parameters |
|
225 | Parameters | |
226 | ---------- |
|
226 | ---------- | |
227 | objs : tuple of objects |
|
227 | objs : tuple of objects | |
228 | The Python objects to display, or if raw=True raw latex data to |
|
228 | The Python objects to display, or if raw=True raw latex data to | |
229 | display. |
|
229 | display. | |
230 | raw : bool |
|
230 | raw : bool | |
231 | Are the data objects raw data or Python objects that need to be |
|
231 | Are the data objects raw data or Python objects that need to be | |
232 | formatted before display? [default: False] |
|
232 | formatted before display? [default: False] | |
233 | metadata : dict (optional) |
|
233 | metadata : dict (optional) | |
234 | Metadata to be associated with the specific mimetype output. |
|
234 | Metadata to be associated with the specific mimetype output. | |
235 | """ |
|
235 | """ | |
236 | _display_mimetype('text/latex', objs, **kwargs) |
|
236 | _display_mimetype('text/latex', objs, **kwargs) | |
237 |
|
237 | |||
238 |
|
238 | |||
239 | def display_json(*objs, **kwargs): |
|
239 | def display_json(*objs, **kwargs): | |
240 | """Display the JSON representation of an object. |
|
240 | """Display the JSON representation of an object. | |
241 |
|
241 | |||
242 | Note that not many frontends support displaying JSON. |
|
242 | Note that not many frontends support displaying JSON. | |
243 |
|
243 | |||
244 | Parameters |
|
244 | Parameters | |
245 | ---------- |
|
245 | ---------- | |
246 | objs : tuple of objects |
|
246 | objs : tuple of objects | |
247 | The Python objects to display, or if raw=True raw json data to |
|
247 | The Python objects to display, or if raw=True raw json data to | |
248 | display. |
|
248 | display. | |
249 | raw : bool |
|
249 | raw : bool | |
250 | Are the data objects raw data or Python objects that need to be |
|
250 | Are the data objects raw data or Python objects that need to be | |
251 | formatted before display? [default: False] |
|
251 | formatted before display? [default: False] | |
252 | metadata : dict (optional) |
|
252 | metadata : dict (optional) | |
253 | Metadata to be associated with the specific mimetype output. |
|
253 | Metadata to be associated with the specific mimetype output. | |
254 | """ |
|
254 | """ | |
255 | _display_mimetype('application/json', objs, **kwargs) |
|
255 | _display_mimetype('application/json', objs, **kwargs) | |
256 |
|
256 | |||
257 |
|
257 | |||
258 | def display_javascript(*objs, **kwargs): |
|
258 | def display_javascript(*objs, **kwargs): | |
259 | """Display the Javascript representation of an object. |
|
259 | """Display the Javascript representation of an object. | |
260 |
|
260 | |||
261 | Parameters |
|
261 | Parameters | |
262 | ---------- |
|
262 | ---------- | |
263 | objs : tuple of objects |
|
263 | objs : tuple of objects | |
264 | The Python objects to display, or if raw=True raw javascript data to |
|
264 | The Python objects to display, or if raw=True raw javascript data to | |
265 | display. |
|
265 | display. | |
266 | raw : bool |
|
266 | raw : bool | |
267 | Are the data objects raw data or Python objects that need to be |
|
267 | Are the data objects raw data or Python objects that need to be | |
268 | formatted before display? [default: False] |
|
268 | formatted before display? [default: False] | |
269 | metadata : dict (optional) |
|
269 | metadata : dict (optional) | |
270 | Metadata to be associated with the specific mimetype output. |
|
270 | Metadata to be associated with the specific mimetype output. | |
271 | """ |
|
271 | """ | |
272 | _display_mimetype('application/javascript', objs, **kwargs) |
|
272 | _display_mimetype('application/javascript', objs, **kwargs) | |
273 |
|
273 | |||
274 |
|
274 | |||
275 | def display_pdf(*objs, **kwargs): |
|
275 | def display_pdf(*objs, **kwargs): | |
276 | """Display the PDF representation of an object. |
|
276 | """Display the PDF representation of an object. | |
277 |
|
277 | |||
278 | Parameters |
|
278 | Parameters | |
279 | ---------- |
|
279 | ---------- | |
280 | objs : tuple of objects |
|
280 | objs : tuple of objects | |
281 | The Python objects to display, or if raw=True raw javascript data to |
|
281 | The Python objects to display, or if raw=True raw javascript data to | |
282 | display. |
|
282 | display. | |
283 | raw : bool |
|
283 | raw : bool | |
284 | Are the data objects raw data or Python objects that need to be |
|
284 | Are the data objects raw data or Python objects that need to be | |
285 | formatted before display? [default: False] |
|
285 | formatted before display? [default: False] | |
286 | metadata : dict (optional) |
|
286 | metadata : dict (optional) | |
287 | Metadata to be associated with the specific mimetype output. |
|
287 | Metadata to be associated with the specific mimetype output. | |
288 | """ |
|
288 | """ | |
289 | _display_mimetype('application/pdf', objs, **kwargs) |
|
289 | _display_mimetype('application/pdf', objs, **kwargs) | |
290 |
|
290 | |||
291 |
|
291 | |||
292 | #----------------------------------------------------------------------------- |
|
292 | #----------------------------------------------------------------------------- | |
293 | # Smart classes |
|
293 | # Smart classes | |
294 | #----------------------------------------------------------------------------- |
|
294 | #----------------------------------------------------------------------------- | |
295 |
|
295 | |||
296 |
|
296 | |||
297 | class DisplayObject(object): |
|
297 | class DisplayObject(object): | |
298 | """An object that wraps data to be displayed.""" |
|
298 | """An object that wraps data to be displayed.""" | |
299 |
|
299 | |||
300 | _read_flags = 'r' |
|
300 | _read_flags = 'r' | |
301 |
|
301 | |||
302 | def __init__(self, data=None, url=None, filename=None): |
|
302 | def __init__(self, data=None, url=None, filename=None): | |
303 | """Create a display object given raw data. |
|
303 | """Create a display object given raw data. | |
304 |
|
304 | |||
305 | When this object is returned by an expression or passed to the |
|
305 | When this object is returned by an expression or passed to the | |
306 | display function, it will result in the data being displayed |
|
306 | display function, it will result in the data being displayed | |
307 | in the frontend. The MIME type of the data should match the |
|
307 | in the frontend. The MIME type of the data should match the | |
308 | subclasses used, so the Png subclass should be used for 'image/png' |
|
308 | subclasses used, so the Png subclass should be used for 'image/png' | |
309 | data. If the data is a URL, the data will first be downloaded |
|
309 | data. If the data is a URL, the data will first be downloaded | |
310 | and then displayed. If |
|
310 | and then displayed. If | |
311 |
|
311 | |||
312 | Parameters |
|
312 | Parameters | |
313 | ---------- |
|
313 | ---------- | |
314 | data : unicode, str or bytes |
|
314 | data : unicode, str or bytes | |
315 | The raw data or a URL or file to load the data from |
|
315 | The raw data or a URL or file to load the data from | |
316 | url : unicode |
|
316 | url : unicode | |
317 | A URL to download the data from. |
|
317 | A URL to download the data from. | |
318 | filename : unicode |
|
318 | filename : unicode | |
319 | Path to a local file to load the data from. |
|
319 | Path to a local file to load the data from. | |
320 | """ |
|
320 | """ | |
321 | if data is not None and isinstance(data, string_types): |
|
321 | if data is not None and isinstance(data, string_types): | |
322 | if data.startswith('http') and url is None: |
|
322 | if data.startswith('http') and url is None: | |
323 | url = data |
|
323 | url = data | |
324 | filename = None |
|
324 | filename = None | |
325 | data = None |
|
325 | data = None | |
326 | elif _safe_exists(data) and filename is None: |
|
326 | elif _safe_exists(data) and filename is None: | |
327 | url = None |
|
327 | url = None | |
328 | filename = data |
|
328 | filename = data | |
329 | data = None |
|
329 | data = None | |
330 |
|
330 | |||
331 | self.data = data |
|
331 | self.data = data | |
332 | self.url = url |
|
332 | self.url = url | |
333 | self.filename = None if filename is None else unicode_type(filename) |
|
333 | self.filename = None if filename is None else unicode_type(filename) | |
334 |
|
334 | |||
335 | self.reload() |
|
335 | self.reload() | |
336 | self._check_data() |
|
336 | self._check_data() | |
337 |
|
337 | |||
338 | def _check_data(self): |
|
338 | def _check_data(self): | |
339 | """Override in subclasses if there's something to check.""" |
|
339 | """Override in subclasses if there's something to check.""" | |
340 | pass |
|
340 | pass | |
341 |
|
341 | |||
342 | def reload(self): |
|
342 | def reload(self): | |
343 | """Reload the raw data from file or URL.""" |
|
343 | """Reload the raw data from file or URL.""" | |
344 | if self.filename is not None: |
|
344 | if self.filename is not None: | |
345 | with open(self.filename, self._read_flags) as f: |
|
345 | with open(self.filename, self._read_flags) as f: | |
346 | self.data = f.read() |
|
346 | self.data = f.read() | |
347 | elif self.url is not None: |
|
347 | elif self.url is not None: | |
348 | try: |
|
348 | try: | |
349 | try: |
|
349 | try: | |
350 | from urllib.request import urlopen # Py3 |
|
350 | from urllib.request import urlopen # Py3 | |
351 | except ImportError: |
|
351 | except ImportError: | |
352 | from urllib2 import urlopen |
|
352 | from urllib2 import urlopen | |
353 | response = urlopen(self.url) |
|
353 | response = urlopen(self.url) | |
354 | self.data = response.read() |
|
354 | self.data = response.read() | |
355 | # extract encoding from header, if there is one: |
|
355 | # extract encoding from header, if there is one: | |
356 | encoding = None |
|
356 | encoding = None | |
357 | for sub in response.headers['content-type'].split(';'): |
|
357 | for sub in response.headers['content-type'].split(';'): | |
358 | sub = sub.strip() |
|
358 | sub = sub.strip() | |
359 | if sub.startswith('charset'): |
|
359 | if sub.startswith('charset'): | |
360 | encoding = sub.split('=')[-1].strip() |
|
360 | encoding = sub.split('=')[-1].strip() | |
361 | break |
|
361 | break | |
362 | # decode data, if an encoding was specified |
|
362 | # decode data, if an encoding was specified | |
363 | if encoding: |
|
363 | if encoding: | |
364 | self.data = self.data.decode(encoding, 'replace') |
|
364 | self.data = self.data.decode(encoding, 'replace') | |
365 | except: |
|
365 | except: | |
366 | self.data = None |
|
366 | self.data = None | |
367 |
|
367 | |||
368 | class TextDisplayObject(DisplayObject): |
|
368 | class TextDisplayObject(DisplayObject): | |
369 | """Validate that display data is text""" |
|
369 | """Validate that display data is text""" | |
370 | def _check_data(self): |
|
370 | def _check_data(self): | |
371 | if self.data is not None and not isinstance(self.data, string_types): |
|
371 | if self.data is not None and not isinstance(self.data, string_types): | |
372 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) |
|
372 | raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data)) | |
373 |
|
373 | |||
374 | class Pretty(TextDisplayObject): |
|
374 | class Pretty(TextDisplayObject): | |
375 |
|
375 | |||
376 | def _repr_pretty_(self): |
|
376 | def _repr_pretty_(self): | |
377 | return self.data |
|
377 | return self.data | |
378 |
|
378 | |||
379 |
|
379 | |||
380 | class HTML(TextDisplayObject): |
|
380 | class HTML(TextDisplayObject): | |
381 |
|
381 | |||
382 | def _repr_html_(self): |
|
382 | def _repr_html_(self): | |
383 | return self.data |
|
383 | return self.data | |
384 |
|
384 | |||
385 | def __html__(self): |
|
385 | def __html__(self): | |
386 | """ |
|
386 | """ | |
387 | This method exists to inform other HTML-using modules (e.g. Markupsafe, |
|
387 | This method exists to inform other HTML-using modules (e.g. Markupsafe, | |
388 | htmltag, etc) that this object is HTML and does not need things like |
|
388 | htmltag, etc) that this object is HTML and does not need things like | |
389 | special characters (<>&) escaped. |
|
389 | special characters (<>&) escaped. | |
390 | """ |
|
390 | """ | |
391 | return self._repr_html_() |
|
391 | return self._repr_html_() | |
392 |
|
392 | |||
393 |
|
393 | |||
394 | class Math(TextDisplayObject): |
|
394 | class Math(TextDisplayObject): | |
395 |
|
395 | |||
396 | def _repr_latex_(self): |
|
396 | def _repr_latex_(self): | |
397 | s = self.data.strip('$') |
|
397 | s = self.data.strip('$') | |
398 | return "$$%s$$" % s |
|
398 | return "$$%s$$" % s | |
399 |
|
399 | |||
400 |
|
400 | |||
401 | class Latex(TextDisplayObject): |
|
401 | class Latex(TextDisplayObject): | |
402 |
|
402 | |||
403 | def _repr_latex_(self): |
|
403 | def _repr_latex_(self): | |
404 | return self.data |
|
404 | return self.data | |
405 |
|
405 | |||
406 |
|
406 | |||
407 | class SVG(DisplayObject): |
|
407 | class SVG(DisplayObject): | |
408 |
|
408 | |||
409 | # wrap data in a property, which extracts the <svg> tag, discarding |
|
409 | # wrap data in a property, which extracts the <svg> tag, discarding | |
410 | # document headers |
|
410 | # document headers | |
411 | _data = None |
|
411 | _data = None | |
412 |
|
412 | |||
413 | @property |
|
413 | @property | |
414 | def data(self): |
|
414 | def data(self): | |
415 | return self._data |
|
415 | return self._data | |
416 |
|
416 | |||
417 | @data.setter |
|
417 | @data.setter | |
418 | def data(self, svg): |
|
418 | def data(self, svg): | |
419 | if svg is None: |
|
419 | if svg is None: | |
420 | self._data = None |
|
420 | self._data = None | |
421 | return |
|
421 | return | |
422 | # parse into dom object |
|
422 | # parse into dom object | |
423 | from xml.dom import minidom |
|
423 | from xml.dom import minidom | |
424 | svg = cast_bytes_py2(svg) |
|
424 | svg = cast_bytes_py2(svg) | |
425 | x = minidom.parseString(svg) |
|
425 | x = minidom.parseString(svg) | |
426 | # get svg tag (should be 1) |
|
426 | # get svg tag (should be 1) | |
427 | found_svg = x.getElementsByTagName('svg') |
|
427 | found_svg = x.getElementsByTagName('svg') | |
428 | if found_svg: |
|
428 | if found_svg: | |
429 | svg = found_svg[0].toxml() |
|
429 | svg = found_svg[0].toxml() | |
430 | else: |
|
430 | else: | |
431 | # fallback on the input, trust the user |
|
431 | # fallback on the input, trust the user | |
432 | # but this is probably an error. |
|
432 | # but this is probably an error. | |
433 | pass |
|
433 | pass | |
434 | svg = cast_unicode(svg) |
|
434 | svg = cast_unicode(svg) | |
435 | self._data = svg |
|
435 | self._data = svg | |
436 |
|
436 | |||
437 | def _repr_svg_(self): |
|
437 | def _repr_svg_(self): | |
438 | return self.data |
|
438 | return self.data | |
439 |
|
439 | |||
440 |
|
440 | |||
441 | class JSON(TextDisplayObject): |
|
441 | class JSON(TextDisplayObject): | |
442 |
|
442 | |||
443 | def _repr_json_(self): |
|
443 | def _repr_json_(self): | |
444 | return self.data |
|
444 | return self.data | |
445 |
|
445 | |||
446 | css_t = """$("head").append($("<link/>").attr({ |
|
446 | css_t = """$("head").append($("<link/>").attr({ | |
447 | rel: "stylesheet", |
|
447 | rel: "stylesheet", | |
448 | type: "text/css", |
|
448 | type: "text/css", | |
449 | href: "%s" |
|
449 | href: "%s" | |
450 | })); |
|
450 | })); | |
451 | """ |
|
451 | """ | |
452 |
|
452 | |||
453 | lib_t1 = """$.getScript("%s", function () { |
|
453 | lib_t1 = """$.getScript("%s", function () { | |
454 | """ |
|
454 | """ | |
455 | lib_t2 = """}); |
|
455 | lib_t2 = """}); | |
456 | """ |
|
456 | """ | |
457 |
|
457 | |||
458 | class Javascript(TextDisplayObject): |
|
458 | class Javascript(TextDisplayObject): | |
459 |
|
459 | |||
460 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): |
|
460 | def __init__(self, data=None, url=None, filename=None, lib=None, css=None): | |
461 | """Create a Javascript display object given raw data. |
|
461 | """Create a Javascript display object given raw data. | |
462 |
|
462 | |||
463 | When this object is returned by an expression or passed to the |
|
463 | When this object is returned by an expression or passed to the | |
464 | display function, it will result in the data being displayed |
|
464 | display function, it will result in the data being displayed | |
465 | in the frontend. If the data is a URL, the data will first be |
|
465 | in the frontend. If the data is a URL, the data will first be | |
466 | downloaded and then displayed. |
|
466 | downloaded and then displayed. | |
467 |
|
467 | |||
468 | In the Notebook, the containing element will be available as `element`, |
|
468 | In the Notebook, the containing element will be available as `element`, | |
469 | and jQuery will be available. The output area starts hidden, so if |
|
469 | and jQuery will be available. The output area starts hidden, so if | |
470 | the js appends content to `element` that should be visible, then |
|
470 | the js appends content to `element` that should be visible, then | |
471 | it must call `container.show()` to unhide the area. |
|
471 | it must call `container.show()` to unhide the area. | |
472 |
|
472 | |||
473 | Parameters |
|
473 | Parameters | |
474 | ---------- |
|
474 | ---------- | |
475 | data : unicode, str or bytes |
|
475 | data : unicode, str or bytes | |
476 | The Javascript source code or a URL to download it from. |
|
476 | The Javascript source code or a URL to download it from. | |
477 | url : unicode |
|
477 | url : unicode | |
478 | A URL to download the data from. |
|
478 | A URL to download the data from. | |
479 | filename : unicode |
|
479 | filename : unicode | |
480 | Path to a local file to load the data from. |
|
480 | Path to a local file to load the data from. | |
481 | lib : list or str |
|
481 | lib : list or str | |
482 | A sequence of Javascript library URLs to load asynchronously before |
|
482 | A sequence of Javascript library URLs to load asynchronously before | |
483 | running the source code. The full URLs of the libraries should |
|
483 | running the source code. The full URLs of the libraries should | |
484 | be given. A single Javascript library URL can also be given as a |
|
484 | be given. A single Javascript library URL can also be given as a | |
485 | string. |
|
485 | string. | |
486 | css: : list or str |
|
486 | css: : list or str | |
487 | A sequence of css files to load before running the source code. |
|
487 | A sequence of css files to load before running the source code. | |
488 | The full URLs of the css files should be given. A single css URL |
|
488 | The full URLs of the css files should be given. A single css URL | |
489 | can also be given as a string. |
|
489 | can also be given as a string. | |
490 | """ |
|
490 | """ | |
491 | if isinstance(lib, string_types): |
|
491 | if isinstance(lib, string_types): | |
492 | lib = [lib] |
|
492 | lib = [lib] | |
493 | elif lib is None: |
|
493 | elif lib is None: | |
494 | lib = [] |
|
494 | lib = [] | |
495 | if isinstance(css, string_types): |
|
495 | if isinstance(css, string_types): | |
496 | css = [css] |
|
496 | css = [css] | |
497 | elif css is None: |
|
497 | elif css is None: | |
498 | css = [] |
|
498 | css = [] | |
499 | if not isinstance(lib, (list,tuple)): |
|
499 | if not isinstance(lib, (list,tuple)): | |
500 | raise TypeError('expected sequence, got: %r' % lib) |
|
500 | raise TypeError('expected sequence, got: %r' % lib) | |
501 | if not isinstance(css, (list,tuple)): |
|
501 | if not isinstance(css, (list,tuple)): | |
502 | raise TypeError('expected sequence, got: %r' % css) |
|
502 | raise TypeError('expected sequence, got: %r' % css) | |
503 | self.lib = lib |
|
503 | self.lib = lib | |
504 | self.css = css |
|
504 | self.css = css | |
505 | super(Javascript, self).__init__(data=data, url=url, filename=filename) |
|
505 | super(Javascript, self).__init__(data=data, url=url, filename=filename) | |
506 |
|
506 | |||
507 | def _repr_javascript_(self): |
|
507 | def _repr_javascript_(self): | |
508 | r = '' |
|
508 | r = '' | |
509 | for c in self.css: |
|
509 | for c in self.css: | |
510 | r += css_t % c |
|
510 | r += css_t % c | |
511 | for l in self.lib: |
|
511 | for l in self.lib: | |
512 | r += lib_t1 % l |
|
512 | r += lib_t1 % l | |
513 | r += self.data |
|
513 | r += self.data | |
514 | r += lib_t2*len(self.lib) |
|
514 | r += lib_t2*len(self.lib) | |
515 | return r |
|
515 | return r | |
516 |
|
516 | |||
517 | # constants for identifying png/jpeg data |
|
517 | # constants for identifying png/jpeg data | |
518 | _PNG = b'\x89PNG\r\n\x1a\n' |
|
518 | _PNG = b'\x89PNG\r\n\x1a\n' | |
519 | _JPEG = b'\xff\xd8' |
|
519 | _JPEG = b'\xff\xd8' | |
520 |
|
520 | |||
521 | def _pngxy(data): |
|
521 | def _pngxy(data): | |
522 | """read the (width, height) from a PNG header""" |
|
522 | """read the (width, height) from a PNG header""" | |
523 | ihdr = data.index(b'IHDR') |
|
523 | ihdr = data.index(b'IHDR') | |
524 | # next 8 bytes are width/height |
|
524 | # next 8 bytes are width/height | |
525 | w4h4 = data[ihdr+4:ihdr+12] |
|
525 | w4h4 = data[ihdr+4:ihdr+12] | |
526 | return struct.unpack('>ii', w4h4) |
|
526 | return struct.unpack('>ii', w4h4) | |
527 |
|
527 | |||
528 | def _jpegxy(data): |
|
528 | def _jpegxy(data): | |
529 | """read the (width, height) from a JPEG header""" |
|
529 | """read the (width, height) from a JPEG header""" | |
530 | # adapted from http://www.64lines.com/jpeg-width-height |
|
530 | # adapted from http://www.64lines.com/jpeg-width-height | |
531 |
|
531 | |||
532 | idx = 4 |
|
532 | idx = 4 | |
533 | while True: |
|
533 | while True: | |
534 | block_size = struct.unpack('>H', data[idx:idx+2])[0] |
|
534 | block_size = struct.unpack('>H', data[idx:idx+2])[0] | |
535 | idx = idx + block_size |
|
535 | idx = idx + block_size | |
536 | if data[idx:idx+2] == b'\xFF\xC0': |
|
536 | if data[idx:idx+2] == b'\xFF\xC0': | |
537 | # found Start of Frame |
|
537 | # found Start of Frame | |
538 | iSOF = idx |
|
538 | iSOF = idx | |
539 | break |
|
539 | break | |
540 | else: |
|
540 | else: | |
541 | # read another block |
|
541 | # read another block | |
542 | idx += 2 |
|
542 | idx += 2 | |
543 |
|
543 | |||
544 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) |
|
544 | h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9]) | |
545 | return w, h |
|
545 | return w, h | |
546 |
|
546 | |||
547 | class Image(DisplayObject): |
|
547 | class Image(DisplayObject): | |
548 |
|
548 | |||
549 | _read_flags = 'rb' |
|
549 | _read_flags = 'rb' | |
550 | _FMT_JPEG = u'jpeg' |
|
550 | _FMT_JPEG = u'jpeg' | |
551 | _FMT_PNG = u'png' |
|
551 | _FMT_PNG = u'png' | |
552 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] |
|
552 | _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG] | |
553 |
|
553 | |||
554 | def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False): |
|
554 | def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False): | |
555 | """Create a PNG/JPEG image object given raw data. |
|
555 | """Create a PNG/JPEG image object given raw data. | |
556 |
|
556 | |||
557 | When this object is returned by an input cell or passed to the |
|
557 | When this object is returned by an input cell or passed to the | |
558 | display function, it will result in the image being displayed |
|
558 | display function, it will result in the image being displayed | |
559 | in the frontend. |
|
559 | in the frontend. | |
560 |
|
560 | |||
561 | Parameters |
|
561 | Parameters | |
562 | ---------- |
|
562 | ---------- | |
563 | data : unicode, str or bytes |
|
563 | data : unicode, str or bytes | |
564 | The raw image data or a URL or filename to load the data from. |
|
564 | The raw image data or a URL or filename to load the data from. | |
565 | This always results in embedded image data. |
|
565 | This always results in embedded image data. | |
566 | url : unicode |
|
566 | url : unicode | |
567 | A URL to download the data from. If you specify `url=`, |
|
567 | A URL to download the data from. If you specify `url=`, | |
568 | the image data will not be embedded unless you also specify `embed=True`. |
|
568 | the image data will not be embedded unless you also specify `embed=True`. | |
569 | filename : unicode |
|
569 | filename : unicode | |
570 | Path to a local file to load the data from. |
|
570 | Path to a local file to load the data from. | |
571 | Images from a file are always embedded. |
|
571 | Images from a file are always embedded. | |
572 | format : unicode |
|
572 | format : unicode | |
573 | The format of the image data (png/jpeg/jpg). If a filename or URL is given |
|
573 | The format of the image data (png/jpeg/jpg). If a filename or URL is given | |
574 | for format will be inferred from the filename extension. |
|
574 | for format will be inferred from the filename extension. | |
575 | embed : bool |
|
575 | embed : bool | |
576 | Should the image data be embedded using a data URI (True) or be |
|
576 | Should the image data be embedded using a data URI (True) or be | |
577 | loaded using an <img> tag. Set this to True if you want the image |
|
577 | loaded using an <img> tag. Set this to True if you want the image | |
578 | to be viewable later with no internet connection in the notebook. |
|
578 | to be viewable later with no internet connection in the notebook. | |
579 |
|
579 | |||
580 | Default is `True`, unless the keyword argument `url` is set, then |
|
580 | Default is `True`, unless the keyword argument `url` is set, then | |
581 | default value is `False`. |
|
581 | default value is `False`. | |
582 |
|
582 | |||
583 | Note that QtConsole is not able to display images if `embed` is set to `False` |
|
583 | Note that QtConsole is not able to display images if `embed` is set to `False` | |
584 | width : int |
|
584 | width : int | |
585 | Width to which to constrain the image in html |
|
585 | Width to which to constrain the image in html | |
586 | height : int |
|
586 | height : int | |
587 | Height to which to constrain the image in html |
|
587 | Height to which to constrain the image in html | |
588 | retina : bool |
|
588 | retina : bool | |
589 | Automatically set the width and height to half of the measured |
|
589 | Automatically set the width and height to half of the measured | |
590 | width and height. |
|
590 | width and height. | |
591 | This only works for embedded images because it reads the width/height |
|
591 | This only works for embedded images because it reads the width/height | |
592 | from image data. |
|
592 | from image data. | |
593 | For non-embedded images, you can just set the desired display width |
|
593 | For non-embedded images, you can just set the desired display width | |
594 | and height directly. |
|
594 | and height directly. | |
595 |
|
595 | |||
596 | Examples |
|
596 | Examples | |
597 | -------- |
|
597 | -------- | |
598 | # embedded image data, works in qtconsole and notebook |
|
598 | # embedded image data, works in qtconsole and notebook | |
599 | # when passed positionally, the first arg can be any of raw image data, |
|
599 | # when passed positionally, the first arg can be any of raw image data, | |
600 | # a URL, or a filename from which to load image data. |
|
600 | # a URL, or a filename from which to load image data. | |
601 | # The result is always embedding image data for inline images. |
|
601 | # The result is always embedding image data for inline images. | |
602 | Image('http://www.google.fr/images/srpr/logo3w.png') |
|
602 | Image('http://www.google.fr/images/srpr/logo3w.png') | |
603 | Image('/path/to/image.jpg') |
|
603 | Image('/path/to/image.jpg') | |
604 | Image(b'RAW_PNG_DATA...') |
|
604 | Image(b'RAW_PNG_DATA...') | |
605 |
|
605 | |||
606 | # Specifying Image(url=...) does not embed the image data, |
|
606 | # Specifying Image(url=...) does not embed the image data, | |
607 | # it only generates `<img>` tag with a link to the source. |
|
607 | # it only generates `<img>` tag with a link to the source. | |
608 | # This will not work in the qtconsole or offline. |
|
608 | # This will not work in the qtconsole or offline. | |
609 | Image(url='http://www.google.fr/images/srpr/logo3w.png') |
|
609 | Image(url='http://www.google.fr/images/srpr/logo3w.png') | |
610 |
|
610 | |||
611 | """ |
|
611 | """ | |
612 | if filename is not None: |
|
612 | if filename is not None: | |
613 | ext = self._find_ext(filename) |
|
613 | ext = self._find_ext(filename) | |
614 | elif url is not None: |
|
614 | elif url is not None: | |
615 | ext = self._find_ext(url) |
|
615 | ext = self._find_ext(url) | |
616 | elif data is None: |
|
616 | elif data is None: | |
617 | raise ValueError("No image data found. Expecting filename, url, or data.") |
|
617 | raise ValueError("No image data found. Expecting filename, url, or data.") | |
618 | elif isinstance(data, string_types) and ( |
|
618 | elif isinstance(data, string_types) and ( | |
619 | data.startswith('http') or _safe_exists(data) |
|
619 | data.startswith('http') or _safe_exists(data) | |
620 | ): |
|
620 | ): | |
621 | ext = self._find_ext(data) |
|
621 | ext = self._find_ext(data) | |
622 | else: |
|
622 | else: | |
623 | ext = None |
|
623 | ext = None | |
624 |
|
624 | |||
625 | if ext is not None: |
|
625 | if ext is not None: | |
626 | format = ext.lower() |
|
626 | format = ext.lower() | |
627 | if ext == u'jpg' or ext == u'jpeg': |
|
627 | if ext == u'jpg' or ext == u'jpeg': | |
628 | format = self._FMT_JPEG |
|
628 | format = self._FMT_JPEG | |
629 | if ext == u'png': |
|
629 | if ext == u'png': | |
630 | format = self._FMT_PNG |
|
630 | format = self._FMT_PNG | |
631 | elif isinstance(data, bytes) and format == 'png': |
|
631 | elif isinstance(data, bytes) and format == 'png': | |
632 | # infer image type from image data header, |
|
632 | # infer image type from image data header, | |
633 | # only if format might not have been specified. |
|
633 | # only if format might not have been specified. | |
634 | if data[:2] == _JPEG: |
|
634 | if data[:2] == _JPEG: | |
635 | format = 'jpeg' |
|
635 | format = 'jpeg' | |
636 |
|
636 | |||
637 | self.format = unicode_type(format).lower() |
|
637 | self.format = unicode_type(format).lower() | |
638 | self.embed = embed if embed is not None else (url is None) |
|
638 | self.embed = embed if embed is not None else (url is None) | |
639 |
|
639 | |||
640 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: |
|
640 | if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS: | |
641 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) |
|
641 | raise ValueError("Cannot embed the '%s' image format" % (self.format)) | |
642 | self.width = width |
|
642 | self.width = width | |
643 | self.height = height |
|
643 | self.height = height | |
644 | self.retina = retina |
|
644 | self.retina = retina | |
645 | super(Image, self).__init__(data=data, url=url, filename=filename) |
|
645 | super(Image, self).__init__(data=data, url=url, filename=filename) | |
646 |
|
646 | |||
647 | if retina: |
|
647 | if retina: | |
648 | self._retina_shape() |
|
648 | self._retina_shape() | |
649 |
|
649 | |||
650 | def _retina_shape(self): |
|
650 | def _retina_shape(self): | |
651 | """load pixel-doubled width and height from image data""" |
|
651 | """load pixel-doubled width and height from image data""" | |
652 | if not self.embed: |
|
652 | if not self.embed: | |
653 | return |
|
653 | return | |
654 | if self.format == 'png': |
|
654 | if self.format == 'png': | |
655 | w, h = _pngxy(self.data) |
|
655 | w, h = _pngxy(self.data) | |
656 | elif self.format == 'jpeg': |
|
656 | elif self.format == 'jpeg': | |
657 | w, h = _jpegxy(self.data) |
|
657 | w, h = _jpegxy(self.data) | |
658 | else: |
|
658 | else: | |
659 | # retina only supports png |
|
659 | # retina only supports png | |
660 | return |
|
660 | return | |
661 | self.width = w // 2 |
|
661 | self.width = w // 2 | |
662 | self.height = h // 2 |
|
662 | self.height = h // 2 | |
663 |
|
663 | |||
664 | def reload(self): |
|
664 | def reload(self): | |
665 | """Reload the raw data from file or URL.""" |
|
665 | """Reload the raw data from file or URL.""" | |
666 | if self.embed: |
|
666 | if self.embed: | |
667 | super(Image,self).reload() |
|
667 | super(Image,self).reload() | |
668 | if self.retina: |
|
668 | if self.retina: | |
669 | self._retina_shape() |
|
669 | self._retina_shape() | |
670 |
|
670 | |||
671 | def _repr_html_(self): |
|
671 | def _repr_html_(self): | |
672 | if not self.embed: |
|
672 | if not self.embed: | |
673 | width = height = '' |
|
673 | width = height = '' | |
674 | if self.width: |
|
674 | if self.width: | |
675 | width = ' width="%d"' % self.width |
|
675 | width = ' width="%d"' % self.width | |
676 | if self.height: |
|
676 | if self.height: | |
677 | height = ' height="%d"' % self.height |
|
677 | height = ' height="%d"' % self.height | |
678 | return u'<img src="%s"%s%s/>' % (self.url, width, height) |
|
678 | return u'<img src="%s"%s%s/>' % (self.url, width, height) | |
679 |
|
679 | |||
680 | def _data_and_metadata(self): |
|
680 | def _data_and_metadata(self): | |
681 | """shortcut for returning metadata with shape information, if defined""" |
|
681 | """shortcut for returning metadata with shape information, if defined""" | |
682 | md = {} |
|
682 | md = {} | |
683 | if self.width: |
|
683 | if self.width: | |
684 | md['width'] = self.width |
|
684 | md['width'] = self.width | |
685 | if self.height: |
|
685 | if self.height: | |
686 | md['height'] = self.height |
|
686 | md['height'] = self.height | |
687 | if md: |
|
687 | if md: | |
688 | return self.data, md |
|
688 | return self.data, md | |
689 | else: |
|
689 | else: | |
690 | return self.data |
|
690 | return self.data | |
691 |
|
691 | |||
692 | def _repr_png_(self): |
|
692 | def _repr_png_(self): | |
693 | if self.embed and self.format == u'png': |
|
693 | if self.embed and self.format == u'png': | |
694 | return self._data_and_metadata() |
|
694 | return self._data_and_metadata() | |
695 |
|
695 | |||
696 | def _repr_jpeg_(self): |
|
696 | def _repr_jpeg_(self): | |
697 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): |
|
697 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): | |
698 | return self._data_and_metadata() |
|
698 | return self._data_and_metadata() | |
699 |
|
699 | |||
700 | def _find_ext(self, s): |
|
700 | def _find_ext(self, s): | |
701 | return unicode_type(s.split('.')[-1].lower()) |
|
701 | return unicode_type(s.split('.')[-1].lower()) | |
702 |
|
702 | |||
703 |
|
703 | |||
704 | def clear_output(wait=False): |
|
704 | def clear_output(wait=False): | |
705 | """Clear the output of the current cell receiving output. |
|
705 | """Clear the output of the current cell receiving output. | |
706 |
|
706 | |||
707 | Parameters |
|
707 | Parameters | |
708 | ---------- |
|
708 | ---------- | |
709 | wait : bool [default: false] |
|
709 | wait : bool [default: false] | |
710 | Wait to clear the output until new output is available to replace it.""" |
|
710 | Wait to clear the output until new output is available to replace it.""" | |
711 | from IPython.core.interactiveshell import InteractiveShell |
|
711 | from IPython.core.interactiveshell import InteractiveShell | |
712 | if InteractiveShell.initialized(): |
|
712 | if InteractiveShell.initialized(): | |
713 | InteractiveShell.instance().display_pub.clear_output(wait) |
|
713 | InteractiveShell.instance().display_pub.clear_output(wait) | |
714 | else: |
|
714 | else: | |
715 | from IPython.utils import io |
|
715 | from IPython.utils import io | |
716 | print('\033[2K\r', file=io.stdout, end='') |
|
716 | print('\033[2K\r', file=io.stdout, end='') | |
717 | io.stdout.flush() |
|
717 | io.stdout.flush() | |
718 | print('\033[2K\r', file=io.stderr, end='') |
|
718 | print('\033[2K\r', file=io.stderr, end='') | |
719 | io.stderr.flush() |
|
719 | io.stderr.flush() | |
|
720 | ||||
|
721 | ||||
|
722 | def select_matplotlib_formats(formats, quality=90): | |||
|
723 | """Select figure formats for the inline backend. | |||
|
724 | ||||
|
725 | Parameters | |||
|
726 | ========== | |||
|
727 | formats : list | |||
|
728 | One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. | |||
|
729 | quality : int | |||
|
730 | A percentage for the quality of JPEG figures. | |||
|
731 | """ | |||
|
732 | from IPython.core.interactiveshell import InteractiveShell | |||
|
733 | from IPython.core.pylabtools import select_figure_formats | |||
|
734 | shell = InteractiveShell.instance() | |||
|
735 | select_figure_formats(shell, formats, quality=90) | |||
|
736 |
@@ -1,356 +1,356 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Pylab (matplotlib) support utilities. |
|
2 | """Pylab (matplotlib) support utilities. | |
3 |
|
3 | |||
4 | Authors |
|
4 | Authors | |
5 | ------- |
|
5 | ------- | |
6 |
|
6 | |||
7 | * Fernando Perez. |
|
7 | * Fernando Perez. | |
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | """ |
|
9 | """ | |
10 | from __future__ import print_function |
|
10 | from __future__ import print_function | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2009 The IPython Development Team |
|
13 | # Copyright (C) 2009 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Imports |
|
20 | # Imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | import sys |
|
23 | import sys | |
24 | from io import BytesIO |
|
24 | from io import BytesIO | |
25 |
|
25 | |||
26 | from IPython.core.display import _pngxy |
|
26 | from IPython.core.display import _pngxy | |
27 | from IPython.utils.decorators import flag_calls |
|
27 | from IPython.utils.decorators import flag_calls | |
28 | from IPython.utils import py3compat |
|
28 | from IPython.utils import py3compat | |
29 |
|
29 | |||
30 | # If user specifies a GUI, that dictates the backend, otherwise we read the |
|
30 | # If user specifies a GUI, that dictates the backend, otherwise we read the | |
31 | # user's mpl default from the mpl rc structure |
|
31 | # user's mpl default from the mpl rc structure | |
32 | backends = {'tk': 'TkAgg', |
|
32 | backends = {'tk': 'TkAgg', | |
33 | 'gtk': 'GTKAgg', |
|
33 | 'gtk': 'GTKAgg', | |
34 | 'gtk3': 'GTK3Agg', |
|
34 | 'gtk3': 'GTK3Agg', | |
35 | 'wx': 'WXAgg', |
|
35 | 'wx': 'WXAgg', | |
36 | 'qt': 'Qt4Agg', # qt3 not supported |
|
36 | 'qt': 'Qt4Agg', # qt3 not supported | |
37 | 'qt4': 'Qt4Agg', |
|
37 | 'qt4': 'Qt4Agg', | |
38 | 'osx': 'MacOSX', |
|
38 | 'osx': 'MacOSX', | |
39 | 'inline' : 'module://IPython.kernel.zmq.pylab.backend_inline'} |
|
39 | 'inline' : 'module://IPython.kernel.zmq.pylab.backend_inline'} | |
40 |
|
40 | |||
41 | # We also need a reverse backends2guis mapping that will properly choose which |
|
41 | # We also need a reverse backends2guis mapping that will properly choose which | |
42 | # GUI support to activate based on the desired matplotlib backend. For the |
|
42 | # GUI support to activate based on the desired matplotlib backend. For the | |
43 | # most part it's just a reverse of the above dict, but we also need to add a |
|
43 | # most part it's just a reverse of the above dict, but we also need to add a | |
44 | # few others that map to the same GUI manually: |
|
44 | # few others that map to the same GUI manually: | |
45 | backend2gui = dict(zip(backends.values(), backends.keys())) |
|
45 | backend2gui = dict(zip(backends.values(), backends.keys())) | |
46 | # Our tests expect backend2gui to just return 'qt' |
|
46 | # Our tests expect backend2gui to just return 'qt' | |
47 | backend2gui['Qt4Agg'] = 'qt' |
|
47 | backend2gui['Qt4Agg'] = 'qt' | |
48 | # In the reverse mapping, there are a few extra valid matplotlib backends that |
|
48 | # In the reverse mapping, there are a few extra valid matplotlib backends that | |
49 | # map to the same GUI support |
|
49 | # map to the same GUI support | |
50 | backend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk' |
|
50 | backend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk' | |
51 | backend2gui['GTK3Cairo'] = 'gtk3' |
|
51 | backend2gui['GTK3Cairo'] = 'gtk3' | |
52 | backend2gui['WX'] = 'wx' |
|
52 | backend2gui['WX'] = 'wx' | |
53 | backend2gui['CocoaAgg'] = 'osx' |
|
53 | backend2gui['CocoaAgg'] = 'osx' | |
54 |
|
54 | |||
55 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
56 | # Matplotlib utilities |
|
56 | # Matplotlib utilities | |
57 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
58 |
|
58 | |||
59 |
|
59 | |||
60 | def getfigs(*fig_nums): |
|
60 | def getfigs(*fig_nums): | |
61 | """Get a list of matplotlib figures by figure numbers. |
|
61 | """Get a list of matplotlib figures by figure numbers. | |
62 |
|
62 | |||
63 | If no arguments are given, all available figures are returned. If the |
|
63 | If no arguments are given, all available figures are returned. If the | |
64 | argument list contains references to invalid figures, a warning is printed |
|
64 | argument list contains references to invalid figures, a warning is printed | |
65 | but the function continues pasting further figures. |
|
65 | but the function continues pasting further figures. | |
66 |
|
66 | |||
67 | Parameters |
|
67 | Parameters | |
68 | ---------- |
|
68 | ---------- | |
69 | figs : tuple |
|
69 | figs : tuple | |
70 | A tuple of ints giving the figure numbers of the figures to return. |
|
70 | A tuple of ints giving the figure numbers of the figures to return. | |
71 | """ |
|
71 | """ | |
72 | from matplotlib._pylab_helpers import Gcf |
|
72 | from matplotlib._pylab_helpers import Gcf | |
73 | if not fig_nums: |
|
73 | if not fig_nums: | |
74 | fig_managers = Gcf.get_all_fig_managers() |
|
74 | fig_managers = Gcf.get_all_fig_managers() | |
75 | return [fm.canvas.figure for fm in fig_managers] |
|
75 | return [fm.canvas.figure for fm in fig_managers] | |
76 | else: |
|
76 | else: | |
77 | figs = [] |
|
77 | figs = [] | |
78 | for num in fig_nums: |
|
78 | for num in fig_nums: | |
79 | f = Gcf.figs.get(num) |
|
79 | f = Gcf.figs.get(num) | |
80 | if f is None: |
|
80 | if f is None: | |
81 | print('Warning: figure %s not available.' % num) |
|
81 | print('Warning: figure %s not available.' % num) | |
82 | else: |
|
82 | else: | |
83 | figs.append(f.canvas.figure) |
|
83 | figs.append(f.canvas.figure) | |
84 | return figs |
|
84 | return figs | |
85 |
|
85 | |||
86 |
|
86 | |||
87 | def figsize(sizex, sizey): |
|
87 | def figsize(sizex, sizey): | |
88 | """Set the default figure size to be [sizex, sizey]. |
|
88 | """Set the default figure size to be [sizex, sizey]. | |
89 |
|
89 | |||
90 | This is just an easy to remember, convenience wrapper that sets:: |
|
90 | This is just an easy to remember, convenience wrapper that sets:: | |
91 |
|
91 | |||
92 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
|
92 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] | |
93 | """ |
|
93 | """ | |
94 | import matplotlib |
|
94 | import matplotlib | |
95 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
|
95 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | def print_figure(fig, fmt='png', quality=90): |
|
98 | def print_figure(fig, fmt='png', quality=90): | |
99 | """Convert a figure to svg, png or jpg for inline display. |
|
99 | """Convert a figure to svg, png or jpg for inline display. | |
100 | Quality is only relevant for jpg. |
|
100 | Quality is only relevant for jpg. | |
101 | """ |
|
101 | """ | |
102 | from matplotlib import rcParams |
|
102 | from matplotlib import rcParams | |
103 | # When there's an empty figure, we shouldn't return anything, otherwise we |
|
103 | # When there's an empty figure, we shouldn't return anything, otherwise we | |
104 | # get big blank areas in the qt console. |
|
104 | # get big blank areas in the qt console. | |
105 | if not fig.axes and not fig.lines: |
|
105 | if not fig.axes and not fig.lines: | |
106 | return |
|
106 | return | |
107 |
|
107 | |||
108 | fc = fig.get_facecolor() |
|
108 | fc = fig.get_facecolor() | |
109 | ec = fig.get_edgecolor() |
|
109 | ec = fig.get_edgecolor() | |
110 | bytes_io = BytesIO() |
|
110 | bytes_io = BytesIO() | |
111 | dpi = rcParams['savefig.dpi'] |
|
111 | dpi = rcParams['savefig.dpi'] | |
112 | if fmt == 'retina': |
|
112 | if fmt == 'retina': | |
113 | dpi = dpi * 2 |
|
113 | dpi = dpi * 2 | |
114 | fmt = 'png' |
|
114 | fmt = 'png' | |
115 | fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight', |
|
115 | fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight', | |
116 | facecolor=fc, edgecolor=ec, dpi=dpi, quality=quality) |
|
116 | facecolor=fc, edgecolor=ec, dpi=dpi, quality=quality) | |
117 | data = bytes_io.getvalue() |
|
117 | data = bytes_io.getvalue() | |
118 | return data |
|
118 | return data | |
119 |
|
119 | |||
120 | def retina_figure(fig): |
|
120 | def retina_figure(fig): | |
121 | """format a figure as a pixel-doubled (retina) PNG""" |
|
121 | """format a figure as a pixel-doubled (retina) PNG""" | |
122 | pngdata = print_figure(fig, fmt='retina') |
|
122 | pngdata = print_figure(fig, fmt='retina') | |
123 | w, h = _pngxy(pngdata) |
|
123 | w, h = _pngxy(pngdata) | |
124 | metadata = dict(width=w//2, height=h//2) |
|
124 | metadata = dict(width=w//2, height=h//2) | |
125 | return pngdata, metadata |
|
125 | return pngdata, metadata | |
126 |
|
126 | |||
127 | # We need a little factory function here to create the closure where |
|
127 | # We need a little factory function here to create the closure where | |
128 | # safe_execfile can live. |
|
128 | # safe_execfile can live. | |
129 | def mpl_runner(safe_execfile): |
|
129 | def mpl_runner(safe_execfile): | |
130 | """Factory to return a matplotlib-enabled runner for %run. |
|
130 | """Factory to return a matplotlib-enabled runner for %run. | |
131 |
|
131 | |||
132 | Parameters |
|
132 | Parameters | |
133 | ---------- |
|
133 | ---------- | |
134 | safe_execfile : function |
|
134 | safe_execfile : function | |
135 | This must be a function with the same interface as the |
|
135 | This must be a function with the same interface as the | |
136 | :meth:`safe_execfile` method of IPython. |
|
136 | :meth:`safe_execfile` method of IPython. | |
137 |
|
137 | |||
138 | Returns |
|
138 | Returns | |
139 | ------- |
|
139 | ------- | |
140 | A function suitable for use as the ``runner`` argument of the %run magic |
|
140 | A function suitable for use as the ``runner`` argument of the %run magic | |
141 | function. |
|
141 | function. | |
142 | """ |
|
142 | """ | |
143 |
|
143 | |||
144 | def mpl_execfile(fname,*where,**kw): |
|
144 | def mpl_execfile(fname,*where,**kw): | |
145 | """matplotlib-aware wrapper around safe_execfile. |
|
145 | """matplotlib-aware wrapper around safe_execfile. | |
146 |
|
146 | |||
147 | Its interface is identical to that of the :func:`execfile` builtin. |
|
147 | Its interface is identical to that of the :func:`execfile` builtin. | |
148 |
|
148 | |||
149 | This is ultimately a call to execfile(), but wrapped in safeties to |
|
149 | This is ultimately a call to execfile(), but wrapped in safeties to | |
150 | properly handle interactive rendering.""" |
|
150 | properly handle interactive rendering.""" | |
151 |
|
151 | |||
152 | import matplotlib |
|
152 | import matplotlib | |
153 | import matplotlib.pylab as pylab |
|
153 | import matplotlib.pylab as pylab | |
154 |
|
154 | |||
155 | #print '*** Matplotlib runner ***' # dbg |
|
155 | #print '*** Matplotlib runner ***' # dbg | |
156 | # turn off rendering until end of script |
|
156 | # turn off rendering until end of script | |
157 | is_interactive = matplotlib.rcParams['interactive'] |
|
157 | is_interactive = matplotlib.rcParams['interactive'] | |
158 | matplotlib.interactive(False) |
|
158 | matplotlib.interactive(False) | |
159 | safe_execfile(fname,*where,**kw) |
|
159 | safe_execfile(fname,*where,**kw) | |
160 | matplotlib.interactive(is_interactive) |
|
160 | matplotlib.interactive(is_interactive) | |
161 | # make rendering call now, if the user tried to do it |
|
161 | # make rendering call now, if the user tried to do it | |
162 | if pylab.draw_if_interactive.called: |
|
162 | if pylab.draw_if_interactive.called: | |
163 | pylab.draw() |
|
163 | pylab.draw() | |
164 | pylab.draw_if_interactive.called = False |
|
164 | pylab.draw_if_interactive.called = False | |
165 |
|
165 | |||
166 | return mpl_execfile |
|
166 | return mpl_execfile | |
167 |
|
167 | |||
168 |
|
168 | |||
169 | def select_figure_format(shell, formats, quality=90): |
|
169 | def select_figure_formats(shell, formats, quality=90): | |
170 | """Select figure formats for the inline backend. |
|
170 | """Select figure formats for the inline backend. | |
171 |
|
171 | |||
172 | Parameters |
|
172 | Parameters | |
173 | ========== |
|
173 | ========== | |
174 | shell : InteractiveShell |
|
174 | shell : InteractiveShell | |
175 | The main IPython instance |
|
175 | The main IPython instance | |
176 | formats : list |
|
176 | formats : list | |
177 | One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. |
|
177 | One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. | |
178 | """ |
|
178 | """ | |
179 | from matplotlib.figure import Figure |
|
179 | from matplotlib.figure import Figure | |
180 | from IPython.kernel.zmq.pylab import backend_inline |
|
180 | from IPython.kernel.zmq.pylab import backend_inline | |
181 |
|
181 | |||
182 | svg_formatter = shell.display_formatter.formatters['image/svg+xml'] |
|
182 | svg_formatter = shell.display_formatter.formatters['image/svg+xml'] | |
183 | png_formatter = shell.display_formatter.formatters['image/png'] |
|
183 | png_formatter = shell.display_formatter.formatters['image/png'] | |
184 | jpg_formatter = shell.display_formatter.formatters['image/jpeg'] |
|
184 | jpg_formatter = shell.display_formatter.formatters['image/jpeg'] | |
185 | pdf_formatter = shell.display_formatter.formatters['application/pdf'] |
|
185 | pdf_formatter = shell.display_formatter.formatters['application/pdf'] | |
186 |
|
186 | |||
187 | if isinstance(formats, py3compat.string_types): |
|
187 | if isinstance(formats, py3compat.string_types): | |
188 | formats = {formats} |
|
188 | formats = {formats} | |
189 |
|
189 | |||
190 | [ f.type_printers.pop(Figure, None) for f in {svg_formatter, png_formatter, jpg_formatter} ] |
|
190 | [ f.type_printers.pop(Figure, None) for f in {svg_formatter, png_formatter, jpg_formatter} ] | |
191 |
|
191 | |||
192 | for fmt in formats: |
|
192 | for fmt in formats: | |
193 | if fmt == 'png': |
|
193 | if fmt == 'png': | |
194 | png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png')) |
|
194 | png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png')) | |
195 | elif fmt in ('png2x', 'retina'): |
|
195 | elif fmt in ('png2x', 'retina'): | |
196 | png_formatter.for_type(Figure, retina_figure) |
|
196 | png_formatter.for_type(Figure, retina_figure) | |
197 | elif fmt in ('jpg', 'jpeg'): |
|
197 | elif fmt in ('jpg', 'jpeg'): | |
198 | jpg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'jpg', quality)) |
|
198 | jpg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'jpg', quality)) | |
199 | elif fmt == 'svg': |
|
199 | elif fmt == 'svg': | |
200 | svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg')) |
|
200 | svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg')) | |
201 | elif fmt == 'pdf': |
|
201 | elif fmt == 'pdf': | |
202 | pdf_formatter.for_type(Figure, lambda fig: print_figure(fig, 'pdf')) |
|
202 | pdf_formatter.for_type(Figure, lambda fig: print_figure(fig, 'pdf')) | |
203 | else: |
|
203 | else: | |
204 | raise ValueError("supported formats are: 'png', 'retina', 'svg', 'jpg', 'pdf' not %r" % fmt) |
|
204 | raise ValueError("supported formats are: 'png', 'retina', 'svg', 'jpg', 'pdf' not %r" % fmt) | |
205 |
|
205 | |||
206 | #----------------------------------------------------------------------------- |
|
206 | #----------------------------------------------------------------------------- | |
207 | # Code for initializing matplotlib and importing pylab |
|
207 | # Code for initializing matplotlib and importing pylab | |
208 | #----------------------------------------------------------------------------- |
|
208 | #----------------------------------------------------------------------------- | |
209 |
|
209 | |||
210 |
|
210 | |||
211 | def find_gui_and_backend(gui=None, gui_select=None): |
|
211 | def find_gui_and_backend(gui=None, gui_select=None): | |
212 | """Given a gui string return the gui and mpl backend. |
|
212 | """Given a gui string return the gui and mpl backend. | |
213 |
|
213 | |||
214 | Parameters |
|
214 | Parameters | |
215 | ---------- |
|
215 | ---------- | |
216 | gui : str |
|
216 | gui : str | |
217 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). |
|
217 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). | |
218 | gui_select : str |
|
218 | gui_select : str | |
219 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). |
|
219 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). | |
220 | This is any gui already selected by the shell. |
|
220 | This is any gui already selected by the shell. | |
221 |
|
221 | |||
222 | Returns |
|
222 | Returns | |
223 | ------- |
|
223 | ------- | |
224 | A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', |
|
224 | A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', | |
225 | 'WXAgg','Qt4Agg','module://IPython.kernel.zmq.pylab.backend_inline'). |
|
225 | 'WXAgg','Qt4Agg','module://IPython.kernel.zmq.pylab.backend_inline'). | |
226 | """ |
|
226 | """ | |
227 |
|
227 | |||
228 | import matplotlib |
|
228 | import matplotlib | |
229 |
|
229 | |||
230 | if gui and gui != 'auto': |
|
230 | if gui and gui != 'auto': | |
231 | # select backend based on requested gui |
|
231 | # select backend based on requested gui | |
232 | backend = backends[gui] |
|
232 | backend = backends[gui] | |
233 | else: |
|
233 | else: | |
234 | # We need to read the backend from the original data structure, *not* |
|
234 | # We need to read the backend from the original data structure, *not* | |
235 | # from mpl.rcParams, since a prior invocation of %matplotlib may have |
|
235 | # from mpl.rcParams, since a prior invocation of %matplotlib may have | |
236 | # overwritten that. |
|
236 | # overwritten that. | |
237 | # WARNING: this assumes matplotlib 1.1 or newer!! |
|
237 | # WARNING: this assumes matplotlib 1.1 or newer!! | |
238 | backend = matplotlib.rcParamsOrig['backend'] |
|
238 | backend = matplotlib.rcParamsOrig['backend'] | |
239 | # In this case, we need to find what the appropriate gui selection call |
|
239 | # In this case, we need to find what the appropriate gui selection call | |
240 | # should be for IPython, so we can activate inputhook accordingly |
|
240 | # should be for IPython, so we can activate inputhook accordingly | |
241 | gui = backend2gui.get(backend, None) |
|
241 | gui = backend2gui.get(backend, None) | |
242 |
|
242 | |||
243 | # If we have already had a gui active, we need it and inline are the |
|
243 | # If we have already had a gui active, we need it and inline are the | |
244 | # ones allowed. |
|
244 | # ones allowed. | |
245 | if gui_select and gui != gui_select: |
|
245 | if gui_select and gui != gui_select: | |
246 | gui = gui_select |
|
246 | gui = gui_select | |
247 | backend = backends[gui] |
|
247 | backend = backends[gui] | |
248 |
|
248 | |||
249 | return gui, backend |
|
249 | return gui, backend | |
250 |
|
250 | |||
251 |
|
251 | |||
252 | def activate_matplotlib(backend): |
|
252 | def activate_matplotlib(backend): | |
253 | """Activate the given backend and set interactive to True.""" |
|
253 | """Activate the given backend and set interactive to True.""" | |
254 |
|
254 | |||
255 | import matplotlib |
|
255 | import matplotlib | |
256 | matplotlib.interactive(True) |
|
256 | matplotlib.interactive(True) | |
257 |
|
257 | |||
258 | # Matplotlib had a bug where even switch_backend could not force |
|
258 | # Matplotlib had a bug where even switch_backend could not force | |
259 | # the rcParam to update. This needs to be set *before* the module |
|
259 | # the rcParam to update. This needs to be set *before* the module | |
260 | # magic of switch_backend(). |
|
260 | # magic of switch_backend(). | |
261 | matplotlib.rcParams['backend'] = backend |
|
261 | matplotlib.rcParams['backend'] = backend | |
262 |
|
262 | |||
263 | import matplotlib.pyplot |
|
263 | import matplotlib.pyplot | |
264 | matplotlib.pyplot.switch_backend(backend) |
|
264 | matplotlib.pyplot.switch_backend(backend) | |
265 |
|
265 | |||
266 | # This must be imported last in the matplotlib series, after |
|
266 | # This must be imported last in the matplotlib series, after | |
267 | # backend/interactivity choices have been made |
|
267 | # backend/interactivity choices have been made | |
268 | import matplotlib.pylab as pylab |
|
268 | import matplotlib.pylab as pylab | |
269 |
|
269 | |||
270 | pylab.show._needmain = False |
|
270 | pylab.show._needmain = False | |
271 | # We need to detect at runtime whether show() is called by the user. |
|
271 | # We need to detect at runtime whether show() is called by the user. | |
272 | # For this, we wrap it into a decorator which adds a 'called' flag. |
|
272 | # For this, we wrap it into a decorator which adds a 'called' flag. | |
273 | pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) |
|
273 | pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) | |
274 |
|
274 | |||
275 |
|
275 | |||
276 | def import_pylab(user_ns, import_all=True): |
|
276 | def import_pylab(user_ns, import_all=True): | |
277 | """Populate the namespace with pylab-related values. |
|
277 | """Populate the namespace with pylab-related values. | |
278 |
|
278 | |||
279 | Imports matplotlib, pylab, numpy, and everything from pylab and numpy. |
|
279 | Imports matplotlib, pylab, numpy, and everything from pylab and numpy. | |
280 |
|
280 | |||
281 | Also imports a few names from IPython (figsize, display, getfigs) |
|
281 | Also imports a few names from IPython (figsize, display, getfigs) | |
282 |
|
282 | |||
283 | """ |
|
283 | """ | |
284 |
|
284 | |||
285 | # Import numpy as np/pyplot as plt are conventions we're trying to |
|
285 | # Import numpy as np/pyplot as plt are conventions we're trying to | |
286 | # somewhat standardize on. Making them available to users by default |
|
286 | # somewhat standardize on. Making them available to users by default | |
287 | # will greatly help this. |
|
287 | # will greatly help this. | |
288 | s = ("import numpy\n" |
|
288 | s = ("import numpy\n" | |
289 | "import matplotlib\n" |
|
289 | "import matplotlib\n" | |
290 | "from matplotlib import pylab, mlab, pyplot\n" |
|
290 | "from matplotlib import pylab, mlab, pyplot\n" | |
291 | "np = numpy\n" |
|
291 | "np = numpy\n" | |
292 | "plt = pyplot\n" |
|
292 | "plt = pyplot\n" | |
293 | ) |
|
293 | ) | |
294 | exec(s, user_ns) |
|
294 | exec(s, user_ns) | |
295 |
|
295 | |||
296 | if import_all: |
|
296 | if import_all: | |
297 | s = ("from matplotlib.pylab import *\n" |
|
297 | s = ("from matplotlib.pylab import *\n" | |
298 | "from numpy import *\n") |
|
298 | "from numpy import *\n") | |
299 | exec(s, user_ns) |
|
299 | exec(s, user_ns) | |
300 |
|
300 | |||
301 | # IPython symbols to add |
|
301 | # IPython symbols to add | |
302 | user_ns['figsize'] = figsize |
|
302 | user_ns['figsize'] = figsize | |
303 | from IPython.core.display import display |
|
303 | from IPython.core.display import display | |
304 | # Add display and getfigs to the user's namespace |
|
304 | # Add display and getfigs to the user's namespace | |
305 | user_ns['display'] = display |
|
305 | user_ns['display'] = display | |
306 | user_ns['getfigs'] = getfigs |
|
306 | user_ns['getfigs'] = getfigs | |
307 |
|
307 | |||
308 |
|
308 | |||
309 | def configure_inline_support(shell, backend): |
|
309 | def configure_inline_support(shell, backend): | |
310 | """Configure an IPython shell object for matplotlib use. |
|
310 | """Configure an IPython shell object for matplotlib use. | |
311 |
|
311 | |||
312 | Parameters |
|
312 | Parameters | |
313 | ---------- |
|
313 | ---------- | |
314 | shell : InteractiveShell instance |
|
314 | shell : InteractiveShell instance | |
315 |
|
315 | |||
316 | backend : matplotlib backend |
|
316 | backend : matplotlib backend | |
317 | """ |
|
317 | """ | |
318 | # If using our svg payload backend, register the post-execution |
|
318 | # If using our svg payload backend, register the post-execution | |
319 | # function that will pick up the results for display. This can only be |
|
319 | # function that will pick up the results for display. This can only be | |
320 | # done with access to the real shell object. |
|
320 | # done with access to the real shell object. | |
321 |
|
321 | |||
322 | # Note: if we can't load the inline backend, then there's no point |
|
322 | # Note: if we can't load the inline backend, then there's no point | |
323 | # continuing (such as in terminal-only shells in environments without |
|
323 | # continuing (such as in terminal-only shells in environments without | |
324 | # zeromq available). |
|
324 | # zeromq available). | |
325 | try: |
|
325 | try: | |
326 | from IPython.kernel.zmq.pylab.backend_inline import InlineBackend |
|
326 | from IPython.kernel.zmq.pylab.backend_inline import InlineBackend | |
327 | except ImportError: |
|
327 | except ImportError: | |
328 | return |
|
328 | return | |
329 | from matplotlib import pyplot |
|
329 | from matplotlib import pyplot | |
330 |
|
330 | |||
331 | cfg = InlineBackend.instance(parent=shell) |
|
331 | cfg = InlineBackend.instance(parent=shell) | |
332 | cfg.shell = shell |
|
332 | cfg.shell = shell | |
333 | if cfg not in shell.configurables: |
|
333 | if cfg not in shell.configurables: | |
334 | shell.configurables.append(cfg) |
|
334 | shell.configurables.append(cfg) | |
335 |
|
335 | |||
336 | if backend == backends['inline']: |
|
336 | if backend == backends['inline']: | |
337 | from IPython.kernel.zmq.pylab.backend_inline import flush_figures |
|
337 | from IPython.kernel.zmq.pylab.backend_inline import flush_figures | |
338 | shell.register_post_execute(flush_figures) |
|
338 | shell.register_post_execute(flush_figures) | |
339 |
|
339 | |||
340 | # Save rcParams that will be overwrittern |
|
340 | # Save rcParams that will be overwrittern | |
341 | shell._saved_rcParams = dict() |
|
341 | shell._saved_rcParams = dict() | |
342 | for k in cfg.rc: |
|
342 | for k in cfg.rc: | |
343 | shell._saved_rcParams[k] = pyplot.rcParams[k] |
|
343 | shell._saved_rcParams[k] = pyplot.rcParams[k] | |
344 | # load inline_rc |
|
344 | # load inline_rc | |
345 | pyplot.rcParams.update(cfg.rc) |
|
345 | pyplot.rcParams.update(cfg.rc) | |
346 | else: |
|
346 | else: | |
347 | from IPython.kernel.zmq.pylab.backend_inline import flush_figures |
|
347 | from IPython.kernel.zmq.pylab.backend_inline import flush_figures | |
348 | if flush_figures in shell._post_execute: |
|
348 | if flush_figures in shell._post_execute: | |
349 | shell._post_execute.pop(flush_figures) |
|
349 | shell._post_execute.pop(flush_figures) | |
350 | if hasattr(shell, '_saved_rcParams'): |
|
350 | if hasattr(shell, '_saved_rcParams'): | |
351 | pyplot.rcParams.update(shell._saved_rcParams) |
|
351 | pyplot.rcParams.update(shell._saved_rcParams) | |
352 | del shell._saved_rcParams |
|
352 | del shell._saved_rcParams | |
353 |
|
353 | |||
354 | # Setup the default figure format |
|
354 | # Setup the default figure format | |
355 | select_figure_format(shell, cfg.figure_formats, cfg.quality) |
|
355 | select_figure_formats(shell, cfg.figure_formats, cfg.quality) | |
356 |
|
356 |
@@ -1,115 +1,115 b'' | |||||
1 | """Configurable for configuring the IPython inline backend |
|
1 | """Configurable for configuring the IPython inline backend | |
2 |
|
2 | |||
3 | This module does not import anything from matplotlib. |
|
3 | This module does not import anything from matplotlib. | |
4 | """ |
|
4 | """ | |
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2011 The IPython Development Team |
|
6 | # Copyright (C) 2011 The IPython Development Team | |
7 | # |
|
7 | # | |
8 | # Distributed under the terms of the BSD License. The full license is in |
|
8 | # Distributed under the terms of the BSD License. The full license is in | |
9 | # the file COPYING, distributed as part of this software. |
|
9 | # the file COPYING, distributed as part of this software. | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Imports |
|
13 | # Imports | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | from IPython.config.configurable import SingletonConfigurable |
|
16 | from IPython.config.configurable import SingletonConfigurable | |
17 | from IPython.utils.traitlets import ( |
|
17 | from IPython.utils.traitlets import ( | |
18 | Dict, Instance, CaselessStrEnum, Set, Bool, Int, TraitError, Unicode |
|
18 | Dict, Instance, CaselessStrEnum, Set, Bool, Int, TraitError, Unicode | |
19 | ) |
|
19 | ) | |
20 | from IPython.utils.warn import warn |
|
20 | from IPython.utils.warn import warn | |
21 |
|
21 | |||
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | # Configurable for inline backend options |
|
23 | # Configurable for inline backend options | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | def pil_available(): |
|
26 | def pil_available(): | |
27 | """Test if PIL/Pillow is available""" |
|
27 | """Test if PIL/Pillow is available""" | |
28 | out = False |
|
28 | out = False | |
29 | try: |
|
29 | try: | |
30 | from PIL import Image |
|
30 | from PIL import Image | |
31 | out = True |
|
31 | out = True | |
32 | except: |
|
32 | except: | |
33 | pass |
|
33 | pass | |
34 | return out |
|
34 | return out | |
35 |
|
35 | |||
36 | # inherit from InlineBackendConfig for deprecation purposes |
|
36 | # inherit from InlineBackendConfig for deprecation purposes | |
37 | class InlineBackendConfig(SingletonConfigurable): |
|
37 | class InlineBackendConfig(SingletonConfigurable): | |
38 | pass |
|
38 | pass | |
39 |
|
39 | |||
40 | class InlineBackend(InlineBackendConfig): |
|
40 | class InlineBackend(InlineBackendConfig): | |
41 | """An object to store configuration of the inline backend.""" |
|
41 | """An object to store configuration of the inline backend.""" | |
42 |
|
42 | |||
43 | def _config_changed(self, name, old, new): |
|
43 | def _config_changed(self, name, old, new): | |
44 | # warn on change of renamed config section |
|
44 | # warn on change of renamed config section | |
45 | if new.InlineBackendConfig != old.InlineBackendConfig: |
|
45 | if new.InlineBackendConfig != old.InlineBackendConfig: | |
46 | warn("InlineBackendConfig has been renamed to InlineBackend") |
|
46 | warn("InlineBackendConfig has been renamed to InlineBackend") | |
47 | super(InlineBackend, self)._config_changed(name, old, new) |
|
47 | super(InlineBackend, self)._config_changed(name, old, new) | |
48 |
|
48 | |||
49 | # The typical default figure size is too large for inline use, |
|
49 | # The typical default figure size is too large for inline use, | |
50 | # so we shrink the figure size to 6x4, and tweak fonts to |
|
50 | # so we shrink the figure size to 6x4, and tweak fonts to | |
51 | # make that fit. |
|
51 | # make that fit. | |
52 | rc = Dict({'figure.figsize': (6.0,4.0), |
|
52 | rc = Dict({'figure.figsize': (6.0,4.0), | |
53 | # play nicely with white background in the Qt and notebook frontend |
|
53 | # play nicely with white background in the Qt and notebook frontend | |
54 | 'figure.facecolor': (1,1,1,0), |
|
54 | 'figure.facecolor': (1,1,1,0), | |
55 | 'figure.edgecolor': (1,1,1,0), |
|
55 | 'figure.edgecolor': (1,1,1,0), | |
56 | # 12pt labels get cutoff on 6x4 logplots, so use 10pt. |
|
56 | # 12pt labels get cutoff on 6x4 logplots, so use 10pt. | |
57 | 'font.size': 10, |
|
57 | 'font.size': 10, | |
58 | # 72 dpi matches SVG/qtconsole |
|
58 | # 72 dpi matches SVG/qtconsole | |
59 | # this only affects PNG export, as SVG has no dpi setting |
|
59 | # this only affects PNG export, as SVG has no dpi setting | |
60 | 'savefig.dpi': 72, |
|
60 | 'savefig.dpi': 72, | |
61 | # 10pt still needs a little more room on the xlabel: |
|
61 | # 10pt still needs a little more room on the xlabel: | |
62 | 'figure.subplot.bottom' : .125 |
|
62 | 'figure.subplot.bottom' : .125 | |
63 | }, config=True, |
|
63 | }, config=True, | |
64 | help="""Subset of matplotlib rcParams that should be different for the |
|
64 | help="""Subset of matplotlib rcParams that should be different for the | |
65 | inline backend.""" |
|
65 | inline backend.""" | |
66 | ) |
|
66 | ) | |
67 |
|
67 | |||
68 | figure_formats = Set({'png'}, config=True, |
|
68 | figure_formats = Set({'png'}, config=True, | |
69 | help="""A set of figure formats to enable: 'png', |
|
69 | help="""A set of figure formats to enable: 'png', | |
70 | 'retina', 'jpeg', 'svg', 'pdf'.""") |
|
70 | 'retina', 'jpeg', 'svg', 'pdf'.""") | |
71 |
|
71 | |||
72 | def _figure_formats_changed(self, name, old, new): |
|
72 | def _figure_formats_changed(self, name, old, new): | |
73 | from IPython.core.pylabtools import select_figure_format |
|
73 | from IPython.core.pylabtools import select_figure_formats | |
74 | if 'jpg' in new or 'jpeg' in new: |
|
74 | if 'jpg' in new or 'jpeg' in new: | |
75 | if not pil_available(): |
|
75 | if not pil_available(): | |
76 | raise TraitError("Requires PIL/Pillow for JPG figures") |
|
76 | raise TraitError("Requires PIL/Pillow for JPG figures") | |
77 | if self.shell is None: |
|
77 | if self.shell is None: | |
78 | return |
|
78 | return | |
79 | else: |
|
79 | else: | |
80 | select_figure_format(self.shell, new) |
|
80 | select_figure_formats(self.shell, new) | |
81 |
|
81 | |||
82 | figure_format = Unicode(config=True, help="""The figure format to enable (deprecated |
|
82 | figure_format = Unicode(config=True, help="""The figure format to enable (deprecated | |
83 | use `figure_formats` instead)""") |
|
83 | use `figure_formats` instead)""") | |
84 |
|
84 | |||
85 | def _figure_format_changed(self, name, old, new): |
|
85 | def _figure_format_changed(self, name, old, new): | |
86 | if new: |
|
86 | if new: | |
87 | self.figure_formats = {new} |
|
87 | self.figure_formats = {new} | |
88 |
|
88 | |||
89 | quality = Int(default_value=90, config=True, |
|
89 | quality = Int(default_value=90, config=True, | |
90 | help="Quality of compression [10-100], currently for lossy JPEG only.") |
|
90 | help="Quality of compression [10-100], currently for lossy JPEG only.") | |
91 |
|
91 | |||
92 | def _quality_changed(self, name, old, new): |
|
92 | def _quality_changed(self, name, old, new): | |
93 | if new < 10 or new > 100: |
|
93 | if new < 10 or new > 100: | |
94 | raise TraitError("figure JPEG quality must be in [10-100] range.") |
|
94 | raise TraitError("figure JPEG quality must be in [10-100] range.") | |
95 |
|
95 | |||
96 | close_figures = Bool(True, config=True, |
|
96 | close_figures = Bool(True, config=True, | |
97 | help="""Close all figures at the end of each cell. |
|
97 | help="""Close all figures at the end of each cell. | |
98 |
|
98 | |||
99 | When True, ensures that each cell starts with no active figures, but it |
|
99 | When True, ensures that each cell starts with no active figures, but it | |
100 | also means that one must keep track of references in order to edit or |
|
100 | also means that one must keep track of references in order to edit or | |
101 | redraw figures in subsequent cells. This mode is ideal for the notebook, |
|
101 | redraw figures in subsequent cells. This mode is ideal for the notebook, | |
102 | where residual plots from other cells might be surprising. |
|
102 | where residual plots from other cells might be surprising. | |
103 |
|
103 | |||
104 | When False, one must call figure() to create new figures. This means |
|
104 | When False, one must call figure() to create new figures. This means | |
105 | that gcf() and getfigs() can reference figures created in other cells, |
|
105 | that gcf() and getfigs() can reference figures created in other cells, | |
106 | and the active figure can continue to be edited with pylab/pyplot |
|
106 | and the active figure can continue to be edited with pylab/pyplot | |
107 | methods that reference the current active figure. This mode facilitates |
|
107 | methods that reference the current active figure. This mode facilitates | |
108 | iterative editing of figures, and behaves most consistently with |
|
108 | iterative editing of figures, and behaves most consistently with | |
109 | other matplotlib backends, but figure barriers between cells must |
|
109 | other matplotlib backends, but figure barriers between cells must | |
110 | be explicit. |
|
110 | be explicit. | |
111 | """) |
|
111 | """) | |
112 |
|
112 | |||
113 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
113 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
114 |
|
114 | |||
115 |
|
115 |
General Comments 0
You need to be logged in to leave comments.
Login now