forked from PBrockmann/ipython_ferretmagic
/
ferretmagic.py
454 lines (381 loc) · 16 KB
/
ferretmagic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# -*- coding: utf-8 -*-
"""
===========
ferretmagic
===========
Magics for interacting with ferret via pyferret.
.. note::
The ``pyferret`` module needs to be installed first
Usage
=====
``%%ferret``
{ferret_DOC}
``%ferret_run``
{ferret_RUN_DOC}
``%ferret_getdata``
{ferret_GETDATA_DOC}
``%ferret_putdata``
{ferret_PUTDATA_DOC}
"""
#-----------------------------------------------------------------------------
# Patrick.Brockmann@lsce.ipsl.fr
# Started 2013/08/28 then put on github.com 2013/09/06
#
# Lock functions are taken from ipythonPexpect magic
# https://cdcvs.fnal.gov/redmine/projects/ipython_ext/repository/revisions/master/raw/ipythonPexpect.py
#-----------------------------------------------------------------------------
import os.path
import tempfile
import math
import pyferret
from shutil import rmtree
from IPython.core.displaypub import publish_display_data
from IPython.core.magic import Magics, magics_class, line_magic, cell_magic, needs_local_scope
from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring
from IPython.utils.py3compat import unicode_to_str
from pexpect import ExceptionPexpect
_PUBLISH_KEY = 'ferretMagic.ferret'
_DEFAULT_PLOTSIZE = '756.0,612.0'
_DEFAULT_MEMSIZE = 400.0
#----------------------------------------------------
class ferretMagicError(Exception):
pass
@magics_class
class ferretMagics(Magics):
"""
A set of magics useful for interactive work with ferret via pyferret.
"""
#----------------------------------------------------
def __init__(self, shell):
"""
Parameters
----------
shell : IPython shell
"""
super(ferretMagics, self).__init__(shell)
try:
pyferret.start(memsize=(_DEFAULT_MEMSIZE/8.0), verify=False, journal=False, unmapped=True, quiet=True)
except ExceptionPexpect:
raise ferretMagicError('pyferret cannot be started')
self._shell = shell
self._shell.ferret_locked = False
#----------------------------------------------------
def ferret_run_code(self, args, code):
"""
Parameters
----------
args : control arguments for running (py)ferret
code : ferret commands to run
"""
# Temporary directory; create under the current directory
# so PDF link files are accessible
temp_dir = tempfile.mkdtemp(dir='.', prefix='ipyferret_').replace('\\', '/')
# Redirect stdout and stderr to file
out_filename = temp_dir + '/output.txt'
(errval, errmsg) = pyferret.run('set redirect /clobber /file="%s" stdout' % out_filename)
# Filename for saving the final plot (if any)
if args.plotname:
plot_filename = str(args.plotname)
if args.pdf:
if not plot_filename.endswith('.pdf'):
plot_filename += '.pdf'
else:
if not plot_filename.endswith('.png'):
plot_filename += '.png'
elif args.pdf:
plot_filename = temp_dir + '/image.pdf'
else:
plot_filename = temp_dir + '/image.png'
# Make it quiet by default
(errval, errmsg) = pyferret.run('cancel mode verify')
if args.memory:
# Reset memory size in megabytes
mem_size = float(args.memory)
if mem_size > 0.0:
(errval, errmsg) = pyferret.run('set memory /size=%f' % (mem_size/8.0))
# Get image size and aspect ratio
if args.size:
plot_size = args.size.split(',')
else:
plot_size = _DEFAULT_PLOTSIZE.split(',')
plot_width = float(plot_size[0])
plot_height = float(plot_size[1])
plot_aspect = plot_height / plot_width
# Set window size with the required aspect ratio;
# always anti-alias with windows of these sizes
if args.bigger:
# Double the canvas size (both width and height) of the standard window
# and double the standard line thickness
canvas_width = 2.0 * math.sqrt(10.5 * 8.5 / plot_aspect)
line_thicken = 2.0
else:
# Use a standard-size window with usual line thickness
canvas_width = math.sqrt(10.5 * 8.5 / plot_aspect)
line_thicken = 1.0
(errval, errmsg) = pyferret.run('set window /xinches=%f /thick=%f /aspect=%f 1' % \
(canvas_width, line_thicken, plot_aspect))
# Run code
pyferret_error = False
for input in code:
# Ignore blank lines
if input:
input = unicode_to_str(input)
(errval, errmsg) = pyferret.run(input)
if errval != pyferret.FERR_OK:
errmsg = errmsg.replace('\\', '<br />')
publish_display_data(_PUBLISH_KEY, {'text/html':
'<pre style="background-color:#F79F81; border-radius: 4px 4px 4px 4px; font-size: smaller">' +
'yes? %s\n' % input +
'%s' % errmsg +
'</pre>'
})
pyferret_error = True
break
# Create the image file; if no final image, no image file will be created.
# Any existing image with that filename will be versioned away ('.~n~' appended)
if not pyferret_error:
if args.pdf:
(errval, errmsg) = pyferret.run('frame /xinch=%f /file="%s" /format=PDF' % (plot_width/72.0, plot_filename) )
else:
(errval, errmsg) = pyferret.run('frame /xpixel=%f /file="%s" /format=PNG' % (plot_width, plot_filename))
if errval != pyferret.FERR_OK:
pyferret_error = True
# Close the window
(errval, errmsg) = pyferret.run('cancel window 1')
# Close the stdout and stderr redirect file
(errval, errmsg) = pyferret.run('cancel redirect')
#-------------------------------
# Publish
display_data = []
# Publish captured stdout text, if any
if os.path.isfile(out_filename) and (os.path.getsize(out_filename) > 0):
try:
text_outputs = []
text_outputs.append('<pre style="background-color:#ECF6CE; border-radius: 4px 4px 4px 4px; font-size: smaller">')
f = open(out_filename, "r")
for line in f:
text_outputs.append(line)
f.close()
text_outputs.append("</pre>")
text_output = "".join(text_outputs)
display_data.append((_PUBLISH_KEY, {'text/html': text_output}))
except:
pass
# Publish image if present
if not pyferret_error:
if args.pdf:
if os.path.isfile(plot_filename):
# Create link to pdf; file visible from cell from files directory
text_outputs = []
text_outputs.append('<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">')
text_outputs.append('Message: <a href="files/%s" target="_blank">%s</a> created.' % (plot_filename, plot_filename))
text_outputs.append('</pre>')
text_output = "".join(text_outputs)
display_data.append((_PUBLISH_KEY, {'text/html': text_output}))
# If the user did not provide the PDF filename,
# do not delete the temporary directory since the PDF is in there.
if args.plotname:
rmtree(temp_dir)
else:
# Delete temporary directory - nothing to preserve
rmtree(temp_dir)
else:
# Display the image in the notebook
try:
f = open(plot_filename, 'rb')
image = f.read().encode('base64')
f.close()
display_data.append((_PUBLISH_KEY, {'text/html': '<div class="myoutput">' +
'<img src="data:image/png;base64,%s"/></div>' % image}))
except:
pass
# Delete temporary directory - PNG encoded in the string
rmtree(temp_dir)
# Publication
for source, data in display_data:
publish_display_data(source, data)
#----------------------------------------------------
@magic_arguments()
@argument(
'-m', '--memory', type=float,
help='Memory, in megabytes, to be used by ferret henceforth. Startup default is %s' % str(_DEFAULT_MEMSIZE)
)
@argument(
'-s', '--size',
help='Pixel size of PNG images, or point size of PDF images, as "width,height". Default is ' + _DEFAULT_PLOTSIZE
)
@argument(
'-b', '--bigger', default=False, action='store_true',
help='Produce a sharper plot by doubling the standard plot window size before scaling'
)
@argument(
'-p', '--pdf', default=False, action='store_true',
help='Generate the output plot as a PDF file.'
)
@argument(
'-f', '--plotname',
help='Name of the image file to create. If not given, a name will be generated.'
)
@cell_magic
def ferret(self, line, cell):
'''
In [10]: %%ferret
....: let a=12
....: list a
The size of output plots can be specified:
In [18]: %%ferret -s 800,600
...: plot i[i=1:100]
'''
args = parse_argstring(self.ferret, line)
code = cell.split('\n')
self.ferret_run_code(args, code)
#----------------------------------------------------
@magic_arguments()
@argument(
'-m', '--memory', type=float,
help='Memory, in megabytes, to be used by ferret henceforth. Startup default is %s' % str(_DEFAULT_MEMSIZE)
)
@argument(
'-s', '--size',
help='Pixel size of PNG images, or point size of PDF images, as "width,height". Default is ' + _DEFAULT_PLOTSIZE
)
@argument(
'-b', '--bigger', default=False, action='store_true',
help='Produce a sharper plot by doubling the standard plot window size before scaling'
)
@argument(
'-p', '--pdf', default=False, action='store_true',
help='Generate the output plot as a PDF file.'
)
@argument(
'-f', '--plotname',
help='Name of the image file to create. If not given, a name will be generated.'
)
@argument(
'string',
nargs='*'
)
@line_magic
def ferret_run(self, line):
'''
Line-level magic to run a command in ferret.
In [12]: for val in [100,500,1000]:
....: %ferret_run -s 400,400 -b 'plot sin(i[i=1:%(val)s]*0.1)' % locals()
'''
args = parse_argstring(self.ferret_run, line)
code = [self.shell.ev(" ".join(args.string))]
self.ferret_run_code(args, code)
#----------------------------------------------------
@magic_arguments()
@argument(
'--create_mask', default=False, action='store_true',
help='The data array associated with the "data" key will be a MaskedArray NumPy array instead an ordinary NumPy array.'
)
@argument(
'code',
nargs='*'
)
@line_magic
def ferret_getdata(self, line):
'''
Line-level magic to get data from ferret.
In [18]: %%ferret
....: use levitus_climatology
In [19]: %ferret_getdata tempdict = temp
....: Message: tempdict is now available in python as a dictionary containing the variable's metadata and data array.
In [20]: print tempdict.keys()
....: ['axis_coords', 'axis_types', 'data_unit', 'axis_units', 'title', 'axis_names', 'missing_value', 'data']
'''
args = parse_argstring(self.ferret_getdata, line)
code = unicode_to_str(''.join(args.code))
pythonvariable = code.split('=')[0]
ferretvariable = code.split('=')[1]
exec('%s = pyferret.getdata("%s", %s)' % (pythonvariable, ferretvariable, args.create_mask) )
self.shell.push("%s" % pythonvariable)
publish_display_data('ferretMagic.ferret', {'text/html':
'<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">' +
'Message: ' + pythonvariable + " is now available in python as a dictionary containing the variable's metadata and data array."
'</pre>'
})
#----------------------------------------------------
@magic_arguments()
@argument(
'--axis_pos', default=None,
help='Order of the axes. Default mode uses a reasonable guess from examining the axis types.'
)
@argument(
'code',
nargs='*'
)
@line_magic
def ferret_putdata(self, line):
'''
Line-level magic to put data to ferret.
In [31]: import numpy as np
....: b = {}
....: b['name']='myvar'
....: b['name']='myvar'
....: x=np.linspace(-np.pi*4, np.pi*4, 500)
....: b['data']=np.sin(x)/x
....: b.keys()
Out[31]: ['data', 'name']
In [32]: %ferret_putdata --axis_pos (1,0,2,3,4,5) b
....: Message: b is now available in ferret as myvar
'''
args = parse_argstring(self.ferret_putdata, line)
ferretvariable = unicode_to_str(args.code[0])
if args.axis_pos:
axis_pos_variable = eval(args.axis_pos)
else:
axis_pos_variable = None
pyferret.putdata(self.shell.user_ns[ferretvariable], axis_pos=axis_pos_variable)
publish_display_data('ferretMagic.ferret', {'text/html':
'<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">' +
'Message: ' + ferretvariable + ' is now available in ferret as ' + self.shell.user_ns[ferretvariable]['name'] +
'</pre>'
})
@line_magic
def ferret_lock(self, line):
'''
Lock the notebook to send EVERY executed cell through pyferret
Do %ferret_unlock to unlock
'''
self._shell.ferret_locked = True
print 'WARNING: All future cell execution will be processed through pyferret!'
print 'To return to IPython, issue %ferret_unlock'
@line_magic
def ferret_unlock(self, line):
'''
Unlock the notebook to return to regular IPython
'''
self._shell.ferret_locked = False
print 'Notebook will use IPython'
# Let's rewrite InteractiveShell.run_cell to do automatic processing with pyferret,
# if desired
from IPython.core.interactiveshell import InteractiveShell
# Let's copy the original "run_cell" method (we do this only once so we can reload)
if not getattr(InteractiveShell, "run_cell_a", False):
InteractiveShell.run_cell_a = InteractiveShell.run_cell
# Now rewrite run_cell
def run_cell_new(self, raw_cell, store_history=False, silent=False, shell_futures=True):
# Are we locked in pyferret?
if getattr(self, "ferret_locked", False):
# Don't alter cells that start with %%ferret or with %ferret_unlock
if raw_cell[:8] == '%%ferret' or raw_cell[:15] == '%ferret_unlock':
pass
else:
# We're going to add a %%ferret to the top
raw_cell = "%%ferret\n" + raw_cell
self.run_cell_a(raw_cell, store_history, silent, shell_futures)
# And assign it
InteractiveShell.run_cell = run_cell_new
#----------------------------------------------------
__doc__ = __doc__.format(
ferret_DOC = ' '*8 + ferretMagics.ferret.__doc__,
ferret_RUN_DOC = ' '*8 + ferretMagics.ferret_run.__doc__,
ferret_GETDATA_DOC = ' '*8 + ferretMagics.ferret_getdata.__doc__,
ferret_PUTDATA_DOC = ' '*8 + ferretMagics.ferret_putdata.__doc__
)
def load_ipython_extension(ip):
"""Load the extension in IPython."""
ip.register_magics(ferretMagics)