Skip to content

Commit 931a766

Browse files
committed
interface for R
mostly a copy-paste of the matlab interface
1 parent 47fe00b commit 931a766

File tree

1 file changed

+129
-0
lines changed
  • nipype/interfaces

1 file changed

+129
-0
lines changed

nipype/interfaces/r.py

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
# -*- coding: utf-8 -*-
2+
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
3+
# vi: set ft=python sts=4 ts=4 sw=4 et:
4+
"""Interfaces to run R scripts."""
5+
import os
6+
7+
from .. import config
8+
from .base import (
9+
CommandLineInputSpec,
10+
InputMultiPath,
11+
isdefined,
12+
CommandLine,
13+
traits,
14+
File,
15+
Directory,
16+
)
17+
18+
19+
def get_r_command():
20+
if "NIPYPE_NO_R" in os.environ:
21+
return None
22+
try:
23+
r_cmd = os.environ["RCMD"]
24+
except:
25+
r_cmd = "R"
26+
return r_cmd
27+
28+
29+
no_r = get_r_command() is None
30+
31+
32+
class RInputSpec(CommandLineInputSpec):
33+
""" Basic expected inputs to R interface """
34+
35+
script = traits.Str(
36+
argstr='-e "%s"', desc="R code to run", mandatory=True, position=-1
37+
)
38+
# non-commandline options
39+
rfile = traits.Bool(True, desc="Run R using R script", usedefault=True)
40+
script_file = File(
41+
"pyscript.R", usedefault=True, desc="Name of file to write R code to"
42+
)
43+
44+
45+
class RCommand(CommandLine):
46+
"""Interface that runs R code
47+
48+
>>> import nipype.interfaces.r as r
49+
>>> r = r.RCommand(rfile=False) # don't write script file
50+
>>> r.inputs.script = "Sys.getenv('USER')"
51+
>>> out = r.run() # doctest: +SKIP
52+
"""
53+
54+
_cmd = "R"
55+
_default_r_cmd = None
56+
_default_rfile = None
57+
input_spec = RInputSpec
58+
59+
def __init__(self, r_cmd=None, **inputs):
60+
"""initializes interface to r
61+
(default 'R')
62+
"""
63+
super(RCommand, self).__init__(**inputs)
64+
if r_cmd and isdefined(r_cmd):
65+
self._cmd = r_cmd
66+
elif self._default_r_cmd:
67+
self._cmd = self._default_r_cmd
68+
69+
if self._default_rfile and not isdefined(self.inputs.rfile):
70+
self.inputs.rfile = self._default_rfile
71+
72+
# For r commands force all output to be returned since r
73+
# does not have a clean way of notifying an error
74+
self.terminal_output = "allatonce"
75+
76+
@classmethod
77+
def set_default_r_cmd(cls, r_cmd):
78+
"""Set the default R command line for R classes.
79+
80+
This method is used to set values for all R
81+
subclasses. However, setting this will not update the output
82+
type for any existing instances. For these, assign the
83+
<instance>.inputs.r_cmd.
84+
"""
85+
cls._default_r_cmd = r_cmd
86+
87+
@classmethod
88+
def set_default_rfile(cls, rfile):
89+
"""Set the default R script file format for R classes.
90+
91+
This method is used to set values for all R
92+
subclasses. However, setting this will not update the output
93+
type for any existing instances. For these, assign the
94+
<instance>.inputs.rfile.
95+
"""
96+
cls._default_rfile = rfile
97+
98+
def _run_interface(self, runtime):
99+
self.terminal_output = "allatonce"
100+
runtime = super(RCommand, self)._run_interface(runtime)
101+
if "R code threw an exception" in runtime.stderr:
102+
self.raise_exception(runtime)
103+
return runtime
104+
105+
def _format_arg(self, name, trait_spec, value):
106+
if name in ["script"]:
107+
argstr = trait_spec.argstr
108+
return self._gen_r_command(argstr, value)
109+
return super(RCommand, self)._format_arg(name, trait_spec, value)
110+
111+
def _gen_r_command(self, argstr, script_lines):
112+
""" Generates commands and, if rfile specified, writes it to disk."""
113+
if not self.inputs.rfile:
114+
# replace newlines with ;, strip comments
115+
script = "; ".join([
116+
line
117+
for line in script_lines.split("\n")
118+
if not line.strip().startswith("#")
119+
])
120+
# escape " and $
121+
script = script.replace('"','\\"')
122+
script = script.replace('$','\\$')
123+
else:
124+
script_path = os.path.join(os.getcwd(), self.inputs.script_file)
125+
with open(script_path, "wt") as rfile:
126+
rfile.write(script_lines)
127+
script = "source('%s')" % script_path
128+
129+
return argstr % script

0 commit comments

Comments
 (0)