~ubuntu-branches/ubuntu/raring/ipython/raring

« back to all changes in this revision

Viewing changes to IPython/extensions/rmagic.py

  • Committer: Package Import Robot
  • Author(s): Julian Taylor
  • Date: 2012-06-30 15:05:32 UTC
  • mfrom: (1.2.18) (6.1.9 sid)
  • Revision ID: package-import@ubuntu.com-20120630150532-c95s7y8qek15kdbo
Tags: 0.13-1
* New upstream release
  No repackging necessary anymore, js sources available in external
  minified variants are not installed
* refresh patches, drop upstream applied full-qt-imports 
* add except-shadows-builtin-fix.patch
* drop libjs-jquery-ui dependency, use the embedded development branch
* don't compress the examples
* remove executable permissions on embedded codemirror files
* build with LC_ALL=C.UTF-8 to avoid a unicode issue in setupbase.py
* remove generated doc images in clean
* update copyright with new and removed files
* remove unreachable Stephan Peijnik from uploaders
  thank you for your work

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding: utf-8 -*-
 
2
"""
 
3
======
 
4
Rmagic
 
5
======
 
6
 
 
7
Magic command interface for interactive work with R via rpy2
 
8
 
 
9
Usage
 
10
=====
 
11
 
 
12
``%R``
 
13
 
 
14
{R_DOC}
 
15
 
 
16
``%Rpush``
 
17
 
 
18
{RPUSH_DOC}
 
19
 
 
20
``%Rpull``
 
21
 
 
22
{RPULL_DOC}
 
23
 
 
24
``%Rget``
 
25
 
 
26
{RGET_DOC}
 
27
 
 
28
"""
 
29
 
 
30
#-----------------------------------------------------------------------------
 
31
#  Copyright (C) 2012 The IPython Development Team
 
32
#
 
33
#  Distributed under the terms of the BSD License.  The full license is in
 
34
#  the file COPYING, distributed as part of this software.
 
35
#-----------------------------------------------------------------------------
 
36
 
 
37
import sys
 
38
import tempfile
 
39
from glob import glob
 
40
from shutil import rmtree
 
41
from getopt import getopt
 
42
 
 
43
# numpy and rpy2 imports
 
44
 
 
45
import numpy as np
 
46
 
 
47
import rpy2.rinterface as ri
 
48
import rpy2.robjects as ro
 
49
from rpy2.robjects.numpy2ri import numpy2ri
 
50
ro.conversion.py2ri = numpy2ri
 
51
 
 
52
# IPython imports
 
53
 
 
54
from IPython.core.displaypub import publish_display_data
 
55
from IPython.core.magic import (Magics, magics_class, cell_magic, line_magic,
 
56
                                line_cell_magic)
 
57
from IPython.testing.skipdoctest import skip_doctest
 
58
from IPython.core.magic_arguments import (
 
59
    argument, magic_arguments, parse_argstring
 
60
)
 
61
from IPython.utils.py3compat import str_to_unicode, unicode_to_str, PY3
 
62
 
 
63
class RInterpreterError(ri.RRuntimeError):
 
64
    """An error when running R code in a %%R magic cell."""
 
65
    def __init__(self, line, err, stdout):
 
66
        self.line = line
 
67
        self.err = err.rstrip()
 
68
        self.stdout = stdout.rstrip()
 
69
    
 
70
    def __unicode__(self):
 
71
        s = 'Failed to parse and evaluate line %r.\nR error message: %r' % \
 
72
                (self.line, self.err)
 
73
        if self.stdout and (self.stdout != self.err):
 
74
            s += '\nR stdout:\n' + self.stdout
 
75
        return s
 
76
    
 
77
    if PY3:
 
78
        __str__ = __unicode__
 
79
    else:
 
80
        def __str__(self):
 
81
            return unicode_to_str(unicode(self), 'utf-8')
 
82
 
 
83
def Rconverter(Robj, dataframe=False):
 
84
    """
 
85
    Convert an object in R's namespace to one suitable
 
86
    for ipython's namespace.
 
87
 
 
88
    For a data.frame, it tries to return a structured array.
 
89
    It first checks for colnames, then names.
 
90
    If all are NULL, it returns np.asarray(Robj), else
 
91
    it tries to construct a recarray
 
92
 
 
93
    Parameters
 
94
    ----------
 
95
 
 
96
    Robj: an R object returned from rpy2
 
97
    """
 
98
    is_data_frame = ro.r('is.data.frame')
 
99
    colnames = ro.r('colnames')
 
100
    rownames = ro.r('rownames') # with pandas, these could be used for the index
 
101
    names = ro.r('names')
 
102
 
 
103
    if dataframe:
 
104
        as_data_frame = ro.r('as.data.frame')
 
105
        cols = colnames(Robj)
 
106
        _names = names(Robj)
 
107
        if cols != ri.NULL:
 
108
            Robj = as_data_frame(Robj)
 
109
            names = tuple(np.array(cols))
 
110
        elif _names != ri.NULL:
 
111
            names = tuple(np.array(_names))
 
112
        else: # failed to find names
 
113
            return np.asarray(Robj)
 
114
        Robj = np.rec.fromarrays(Robj, names = names)
 
115
    return np.asarray(Robj)
 
116
 
 
117
@magics_class
 
118
class RMagics(Magics):
 
119
    """A set of magics useful for interactive work with R via rpy2.
 
120
    """
 
121
 
 
122
    def __init__(self, shell, Rconverter=Rconverter,
 
123
                 pyconverter=np.asarray,
 
124
                 cache_display_data=False):
 
125
        """
 
126
        Parameters
 
127
        ----------
 
128
 
 
129
        shell : IPython shell
 
130
 
 
131
        pyconverter : callable
 
132
            To be called on values in ipython namespace before 
 
133
            assigning to variables in rpy2.
 
134
 
 
135
        cache_display_data : bool
 
136
            If True, the published results of the final call to R are 
 
137
            cached in the variable 'display_cache'.
 
138
 
 
139
        """
 
140
        super(RMagics, self).__init__(shell)
 
141
        self.cache_display_data = cache_display_data
 
142
 
 
143
        self.r = ro.R()
 
144
 
 
145
        self.Rstdout_cache = []
 
146
        self.pyconverter = pyconverter
 
147
        self.Rconverter = Rconverter
 
148
 
 
149
    def eval(self, line):
 
150
        '''
 
151
        Parse and evaluate a line with rpy2.
 
152
        Returns the output to R's stdout() connection
 
153
        and the value of eval(parse(line)).
 
154
        '''
 
155
        old_writeconsole = ri.get_writeconsole()
 
156
        ri.set_writeconsole(self.write_console)
 
157
        try:
 
158
            value = ri.baseenv['eval'](ri.parse(line))
 
159
        except (ri.RRuntimeError, ValueError) as exception:
 
160
            warning_or_other_msg = self.flush() # otherwise next return seems to have copy of error
 
161
            raise RInterpreterError(line, str_to_unicode(str(exception)), warning_or_other_msg)
 
162
        text_output = self.flush()
 
163
        ri.set_writeconsole(old_writeconsole)
 
164
        return text_output, value
 
165
 
 
166
    def write_console(self, output):
 
167
        '''
 
168
        A hook to capture R's stdout in a cache.
 
169
        '''
 
170
        self.Rstdout_cache.append(output)
 
171
 
 
172
    def flush(self):
 
173
        '''
 
174
        Flush R's stdout cache to a string, returning the string.
 
175
        '''
 
176
        value = ''.join([str_to_unicode(s, 'utf-8') for s in self.Rstdout_cache])
 
177
        self.Rstdout_cache = []
 
178
        return value
 
179
 
 
180
    @skip_doctest
 
181
    @line_magic
 
182
    def Rpush(self, line):
 
183
        '''
 
184
        A line-level magic for R that pushes
 
185
        variables from python to rpy2. The line should be made up
 
186
        of whitespace separated variable names in the IPython
 
187
        namespace::
 
188
 
 
189
            In [7]: import numpy as np
 
190
 
 
191
            In [8]: X = np.array([4.5,6.3,7.9])
 
192
 
 
193
            In [9]: X.mean()
 
194
            Out[9]: 6.2333333333333343
 
195
 
 
196
            In [10]: %Rpush X
 
197
 
 
198
            In [11]: %R mean(X)
 
199
            Out[11]: array([ 6.23333333])
 
200
 
 
201
        '''
 
202
 
 
203
        inputs = line.split(' ')
 
204
        for input in inputs:
 
205
            self.r.assign(input, self.pyconverter(self.shell.user_ns[input]))
 
206
 
 
207
    @skip_doctest
 
208
    @magic_arguments()
 
209
    @argument(
 
210
        '-d', '--as_dataframe', action='store_true',
 
211
        default=False,
 
212
        help='Convert objects to data.frames before returning to ipython.'
 
213
        )
 
214
    @argument(
 
215
        'outputs',
 
216
        nargs='*',
 
217
        )
 
218
    @line_magic
 
219
    def Rpull(self, line):
 
220
        '''
 
221
        A line-level magic for R that pulls
 
222
        variables from python to rpy2::
 
223
 
 
224
            In [18]: _ = %R x = c(3,4,6.7); y = c(4,6,7); z = c('a',3,4)
 
225
 
 
226
            In [19]: %Rpull x  y z
 
227
 
 
228
            In [20]: x
 
229
            Out[20]: array([ 3. ,  4. ,  6.7])
 
230
 
 
231
            In [21]: y
 
232
            Out[21]: array([ 4.,  6.,  7.])
 
233
 
 
234
            In [22]: z
 
235
            Out[22]:
 
236
            array(['a', '3', '4'],
 
237
                  dtype='|S1')
 
238
 
 
239
 
 
240
        If --as_dataframe, then each object is returned as a structured array
 
241
        after first passed through "as.data.frame" in R before
 
242
        being calling self.Rconverter. 
 
243
        This is useful when a structured array is desired as output, or
 
244
        when the object in R has mixed data types. 
 
245
        See the %%R docstring for more examples.
 
246
 
 
247
        Notes
 
248
        -----
 
249
 
 
250
        Beware that R names can have '.' so this is not fool proof.
 
251
        To avoid this, don't name your R objects with '.'s...
 
252
 
 
253
        '''
 
254
        args = parse_argstring(self.Rpull, line)
 
255
        outputs = args.outputs
 
256
        for output in outputs:
 
257
            self.shell.push({output:self.Rconverter(self.r(output),dataframe=args.as_dataframe)})
 
258
 
 
259
    @skip_doctest
 
260
    @magic_arguments()
 
261
    @argument(
 
262
        '-d', '--as_dataframe', action='store_true',
 
263
        default=False,
 
264
        help='Convert objects to data.frames before returning to ipython.'
 
265
        )
 
266
    @argument(
 
267
        'output',
 
268
        nargs=1,
 
269
        type=str,
 
270
        )
 
271
    @line_magic
 
272
    def Rget(self, line):
 
273
        '''
 
274
        Return an object from rpy2, possibly as a structured array (if possible).
 
275
        Similar to Rpull except only one argument is accepted and the value is 
 
276
        returned rather than pushed to self.shell.user_ns::
 
277
 
 
278
            In [3]: dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')]
 
279
 
 
280
            In [4]: datapy = np.array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5, 'e')], dtype=dtype)
 
281
 
 
282
            In [5]: %R -i datapy
 
283
 
 
284
            In [6]: %Rget datapy
 
285
            Out[6]: 
 
286
            array([['1', '2', '3', '4'],
 
287
                   ['2', '3', '2', '5'],
 
288
                   ['a', 'b', 'c', 'e']], 
 
289
                  dtype='|S1')
 
290
 
 
291
            In [7]: %Rget -d datapy
 
292
            Out[7]: 
 
293
            array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5.0, 'e')], 
 
294
                  dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')])
 
295
 
 
296
        '''
 
297
        args = parse_argstring(self.Rget, line)
 
298
        output = args.output
 
299
        return self.Rconverter(self.r(output[0]),dataframe=args.as_dataframe)
 
300
 
 
301
 
 
302
    @skip_doctest
 
303
    @magic_arguments()
 
304
    @argument(
 
305
        '-i', '--input', action='append',
 
306
        help='Names of input variable from shell.user_ns to be assigned to R variables of the same names after calling self.pyconverter. Multiple names can be passed separated only by commas with no whitespace.'
 
307
        )
 
308
    @argument(
 
309
        '-o', '--output', action='append',
 
310
        help='Names of variables to be pushed from rpy2 to shell.user_ns after executing cell body and applying self.Rconverter. Multiple names can be passed separated only by commas with no whitespace.'
 
311
        )
 
312
    @argument(
 
313
        '-w', '--width', type=int,
 
314
        help='Width of png plotting device sent as an argument to *png* in R.'
 
315
        )
 
316
    @argument(
 
317
        '-h', '--height', type=int,
 
318
        help='Height of png plotting device sent as an argument to *png* in R.'
 
319
        )
 
320
 
 
321
    @argument(
 
322
        '-d', '--dataframe', action='append',
 
323
        help='Convert these objects to data.frames and return as structured arrays.'
 
324
        )
 
325
    @argument(
 
326
        '-u', '--units', type=int,
 
327
        help='Units of png plotting device sent as an argument to *png* in R. One of ["px", "in", "cm", "mm"].'
 
328
        )
 
329
    @argument(
 
330
        '-p', '--pointsize', type=int,
 
331
        help='Pointsize of png plotting device sent as an argument to *png* in R.'
 
332
        )
 
333
    @argument(
 
334
        '-b', '--bg',
 
335
        help='Background of png plotting device sent as an argument to *png* in R.'
 
336
        )
 
337
    @argument(
 
338
        '-n', '--noreturn',
 
339
        help='Force the magic to not return anything.',
 
340
        action='store_true',
 
341
        default=False
 
342
        )
 
343
    @argument(
 
344
        'code',
 
345
        nargs='*',
 
346
        )
 
347
    @line_cell_magic
 
348
    def R(self, line, cell=None):
 
349
        '''
 
350
        Execute code in R, and pull some of the results back into the Python namespace.
 
351
 
 
352
        In line mode, this will evaluate an expression and convert the returned value to a Python object.
 
353
        The return value is determined by rpy2's behaviour of returning the result of evaluating the
 
354
        final line. 
 
355
 
 
356
        Multiple R lines can be executed by joining them with semicolons::
 
357
 
 
358
            In [9]: %R X=c(1,4,5,7); sd(X); mean(X)
 
359
            Out[9]: array([ 4.25])
 
360
 
 
361
        As a cell, this will run a block of R code, without bringing anything back by default::
 
362
 
 
363
            In [10]: %%R
 
364
               ....: Y = c(2,4,3,9)
 
365
               ....: print(summary(lm(Y~X)))
 
366
               ....:
 
367
 
 
368
            Call:
 
369
            lm(formula = Y ~ X)
 
370
 
 
371
            Residuals:
 
372
                1     2     3     4
 
373
             0.88 -0.24 -2.28  1.64
 
374
 
 
375
            Coefficients:
 
376
                        Estimate Std. Error t value Pr(>|t|)
 
377
            (Intercept)   0.0800     2.3000   0.035    0.975
 
378
            X             1.0400     0.4822   2.157    0.164
 
379
 
 
380
            Residual standard error: 2.088 on 2 degrees of freedom
 
381
            Multiple R-squared: 0.6993,Adjusted R-squared: 0.549
 
382
            F-statistic: 4.651 on 1 and 2 DF,  p-value: 0.1638
 
383
 
 
384
        In the notebook, plots are published as the output of the cell.
 
385
 
 
386
        %R plot(X, Y)
 
387
 
 
388
        will create a scatter plot of X bs Y.
 
389
 
 
390
        If cell is not None and line has some R code, it is prepended to
 
391
        the R code in cell.
 
392
 
 
393
        Objects can be passed back and forth between rpy2 and python via the -i -o flags in line::
 
394
 
 
395
            In [14]: Z = np.array([1,4,5,10])
 
396
 
 
397
            In [15]: %R -i Z mean(Z)
 
398
            Out[15]: array([ 5.])
 
399
 
 
400
 
 
401
            In [16]: %R -o W W=Z*mean(Z)
 
402
            Out[16]: array([  5.,  20.,  25.,  50.])
 
403
 
 
404
            In [17]: W
 
405
            Out[17]: array([  5.,  20.,  25.,  50.])
 
406
 
 
407
        The return value is determined by these rules:
 
408
 
 
409
        * If the cell is not None, the magic returns None.
 
410
 
 
411
        * If the cell evaluates as False, the resulting value is returned
 
412
        unless the final line prints something to the console, in
 
413
        which case None is returned.
 
414
 
 
415
        * If the final line results in a NULL value when evaluated
 
416
        by rpy2, then None is returned.
 
417
 
 
418
        * No attempt is made to convert the final value to a structured array.
 
419
        Use the --dataframe flag or %Rget to push / return a structured array.
 
420
 
 
421
        * If the -n flag is present, there is no return value.
 
422
 
 
423
        * A trailing ';' will also result in no return value as the last
 
424
        value in the line is an empty string.
 
425
 
 
426
        The --dataframe argument will attempt to return structured arrays. 
 
427
        This is useful for dataframes with
 
428
        mixed data types. Note also that for a data.frame, 
 
429
        if it is returned as an ndarray, it is transposed::
 
430
 
 
431
            In [18]: dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')]
 
432
 
 
433
            In [19]: datapy = np.array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5, 'e')], dtype=dtype)
 
434
 
 
435
            In [20]: %%R -o datar
 
436
            datar = datapy
 
437
               ....: 
 
438
 
 
439
            In [21]: datar
 
440
            Out[21]: 
 
441
            array([['1', '2', '3', '4'],
 
442
                   ['2', '3', '2', '5'],
 
443
                   ['a', 'b', 'c', 'e']], 
 
444
                  dtype='|S1')
 
445
 
 
446
            In [22]: %%R -d datar
 
447
            datar = datapy
 
448
               ....: 
 
449
 
 
450
            In [23]: datar
 
451
            Out[23]: 
 
452
            array([(1, 2.9, 'a'), (2, 3.5, 'b'), (3, 2.1, 'c'), (4, 5.0, 'e')], 
 
453
                  dtype=[('x', '<i4'), ('y', '<f8'), ('z', '|S1')])
 
454
 
 
455
        The --dataframe argument first tries colnames, then names.
 
456
        If both are NULL, it returns an ndarray (i.e. unstructured)::
 
457
 
 
458
            In [1]: %R mydata=c(4,6,8.3); NULL
 
459
 
 
460
            In [2]: %R -d mydata
 
461
 
 
462
            In [3]: mydata
 
463
            Out[3]: array([ 4. ,  6. ,  8.3])
 
464
 
 
465
            In [4]: %R names(mydata) = c('a','b','c'); NULL
 
466
 
 
467
            In [5]: %R -d mydata
 
468
 
 
469
            In [6]: mydata
 
470
            Out[6]: 
 
471
            array((4.0, 6.0, 8.3), 
 
472
                  dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])
 
473
 
 
474
            In [7]: %R -o mydata
 
475
 
 
476
            In [8]: mydata
 
477
            Out[8]: array([ 4. ,  6. ,  8.3])
 
478
 
 
479
        '''
 
480
 
 
481
        args = parse_argstring(self.R, line)
 
482
 
 
483
        # arguments 'code' in line are prepended to
 
484
        # the cell lines
 
485
        if not cell:
 
486
            code = ''
 
487
            return_output = True
 
488
            line_mode = True
 
489
        else:
 
490
            code = cell
 
491
            return_output = False
 
492
            line_mode = False
 
493
 
 
494
        code = ' '.join(args.code) + code
 
495
 
 
496
        if args.input:
 
497
            for input in ','.join(args.input).split(','):
 
498
                self.r.assign(input, self.pyconverter(self.shell.user_ns[input]))
 
499
 
 
500
        png_argdict = dict([(n, getattr(args, n)) for n in ['units', 'height', 'width', 'bg', 'pointsize']])
 
501
        png_args = ','.join(['%s=%s' % (o,v) for o, v in png_argdict.items() if v is not None])
 
502
        # execute the R code in a temporary directory
 
503
 
 
504
        tmpd = tempfile.mkdtemp()
 
505
        self.r('png("%s/Rplots%%03d.png",%s)' % (tmpd, png_args))
 
506
 
 
507
        text_output = ''
 
508
        if line_mode:
 
509
            for line in code.split(';'):
 
510
                text_result, result = self.eval(line)
 
511
                text_output += text_result
 
512
            if text_result:
 
513
                # the last line printed something to the console so we won't return it
 
514
                return_output = False
 
515
        else:
 
516
            text_result, result = self.eval(code)
 
517
            text_output += text_result
 
518
 
 
519
        self.r('dev.off()')
 
520
 
 
521
        # read out all the saved .png files
 
522
 
 
523
        images = [open(imgfile, 'rb').read() for imgfile in glob("%s/Rplots*png" % tmpd)]
 
524
 
 
525
        # now publish the images
 
526
        # mimicking IPython/zmq/pylab/backend_inline.py
 
527
        fmt = 'png'
 
528
        mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' }
 
529
        mime = mimetypes[fmt]
 
530
 
 
531
        # publish the printed R objects, if any
 
532
 
 
533
        display_data = []
 
534
        if text_output:
 
535
            display_data.append(('RMagic.R', {'text/plain':text_output}))
 
536
 
 
537
        # flush text streams before sending figures, helps a little with output
 
538
        for image in images:
 
539
            # synchronization in the console (though it's a bandaid, not a real sln)
 
540
            sys.stdout.flush(); sys.stderr.flush()
 
541
            display_data.append(('RMagic.R', {mime: image}))
 
542
 
 
543
        # kill the temporary directory
 
544
        rmtree(tmpd)
 
545
 
 
546
        # try to turn every output into a numpy array
 
547
        # this means that output are assumed to be castable
 
548
        # as numpy arrays
 
549
 
 
550
        if args.output:
 
551
            for output in ','.join(args.output).split(','):
 
552
                self.shell.push({output:self.Rconverter(self.r(output), dataframe=False)})
 
553
 
 
554
        if args.dataframe:
 
555
            for output in ','.join(args.dataframe).split(','):
 
556
                self.shell.push({output:self.Rconverter(self.r(output), dataframe=True)})
 
557
 
 
558
        for tag, disp_d in display_data:
 
559
            publish_display_data(tag, disp_d)
 
560
 
 
561
        # this will keep a reference to the display_data
 
562
        # which might be useful to other objects who happen to use
 
563
        # this method
 
564
 
 
565
        if self.cache_display_data:
 
566
            self.display_cache = display_data
 
567
 
 
568
        # if in line mode and return_output, return the result as an ndarray
 
569
        if return_output and not args.noreturn:
 
570
            if result != ri.NULL:
 
571
                return self.Rconverter(result, dataframe=False)
 
572
 
 
573
__doc__ = __doc__.format(
 
574
                R_DOC = ' '*8 + RMagics.R.__doc__,
 
575
                RPUSH_DOC = ' '*8 + RMagics.Rpush.__doc__,
 
576
                RPULL_DOC = ' '*8 + RMagics.Rpull.__doc__,
 
577
                RGET_DOC = ' '*8 + RMagics.Rget.__doc__
 
578
)
 
579
 
 
580
 
 
581
_loaded = False
 
582
def load_ipython_extension(ip):
 
583
    """Load the extension in IPython."""
 
584
    global _loaded
 
585
    if not _loaded:
 
586
        ip.register_magics(RMagics)
 
587
        _loaded = True