Class: RSRuby

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/rsruby.rb,
ext/rsruby.c

Overview

Synopsis

This class represents the embedded R interpreter. The Singleton module is mixed in to ensure that only one R interpreter is running in a script at any one time and that the interpreter can always be easily accessed without using a global variable.

The R interpreter is started by calling RSRuby.instance. The returned object represents the R interpreter and R functions are called by calling methods on this object:

r = RSRuby.instance
r.sum(1,2,3)
puts r.t_test(1,2,3)['p-value']

See the manual for more details on calling functions and the conversion system for passing data between Ruby and R. If no suitable conversion from R to Ruby is found, an RObj is returned (all R functions are returned as instances of RObj). –

Copyright © 2006 Alex Gutteridge

The Original Code is the RPy python module.

The Initial Developer of the Original Code is Walter Moreira. Portions created by the Initial Developer are Copyright © 2002 the Initial Developer. All Rights Reserved.

Contributor(s): Gregory R. Warnes <[email protected]> (RPy Maintainer)

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ++

Constant Summary collapse

VERSION =
'0.4.3'
TOP_CONVERSION =

Constants for conversion modes

4
PROC_CONVERSION =
4
CLASS_CONVERSION =
3
BASIC_CONVERSION =
2
VECTOR_CONVERSION =
1
NO_CONVERSION =
0
NO_DEFAULT =
-1

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeObject

Starts the R interpreter.



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
# File 'lib/rsruby.rb', line 74

def initialize()

  #Initialize in C
  c_initialize

  @@default_mode = NO_DEFAULT

  @@class_table = {}
  @@proc_table  = {}

  #Setup R object cache
  @@cache = {}
  @@cache['get'] = self.get_fun('get')

  #Get constants
  @@cache['TRUE']  = self.__getitem__('T')
  @@cache['FALSE'] = self.__getitem__('F')
  @@cache['NA']    = self.eval_R('NA')
  # @@cache['NAN']   = self.eval_R('as.double(NA)')
  @@cache['NaN']   = self.eval_R('NaN')
  
  #help!
  @@cache['helpfun'] = self.with_mode(NO_CONVERSION, self.__getitem__('help'))

  #Catch errors
  self.eval_R("options(error=expression(NULL))")
  #disable errors
  self.options('show.error.messages' => false)

end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(r_id, *args) ⇒ Object

Handles method name conversion and calling of R functions If called without args the R function/varialbe is returned rather than called.



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/rsruby.rb', line 108

def method_missing(r_id,*args)

  #Translate Ruby method call to R
  robj_name = RSRuby.convert_method_name(r_id.to_s)

  #Retrieve it
  robj = self.__getitem__(robj_name)

  #TODO perhaps this is not neccessary - always call these methods
  #use the [] syntax for variables etc...
  if args.length > 0

    #convert arguments to lcall format
    lcall_args = RSRuby.convert_args_to_lcall(args)
    
    #Return result of calling object with lcall 
    #formatted args
    return robj.lcall(lcall_args)

  end

  return robj

end

Class Method Details

.convert_args_to_lcall(args) ⇒ Object

Converts an Array of function arguments into lcall format. If the last element of the array is a Hash then the contents of the Hash are interpreted as named arguments.

The returned value is an Array of tuples (Arrays of length two). Each tupple corresponds to a name/argument pair.

For example:

convert_args_to_lcall([1,2,3,{:a=>4,:b=>5}) 
=> [['',1],['',2],['',3],['a',4],['b',5]]


176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/rsruby.rb', line 176

def RSRuby.convert_args_to_lcall(args)

  lcall_args = []
  
  args.each_with_index do |arg,i|
    unless arg.kind_of?(Hash) and i == args.length-1
      lcall_args.push(['',arg])
    else
      arg.each do |k,v|
        lcall_args.push([k.to_s,v])
      end
    end
  end

  return lcall_args

end

.convert_method_name(name) ⇒ Object

Converts a String representing a ‘Ruby-style’ R function name into a String with the real R name according to the rules given in the manual.



157
158
159
160
161
162
163
164
# File 'lib/rsruby.rb', line 157

def RSRuby.convert_method_name(name)
  if name.length > 1 and name[-1].chr == '_' and name[-2].chr != '_'
    name = name[0..-2]
  end
  name.gsub!(/__/,'<-')
  name.gsub!(/_/, '.')
  return name
end

.get_default_modeObject

Returns the current default conversion mode as an Integer.



203
204
205
# File 'lib/rsruby.rb', line 203

def RSRuby.get_default_mode
  @@default_mode
end

.get_rsruby_inputObject

TODO - not implemented



213
214
215
# File 'lib/rsruby.rb', line 213

def RSRuby.get_rsruby_input
  @@rsruby_input
end

.get_rsruby_outputObject

TODO - not implemented



223
224
225
# File 'lib/rsruby.rb', line 223

def RSRuby.get_rsruby_output
  @@rsruby_output
end

.get_rsruby_showfilesObject

TODO - not implemented



233
234
235
# File 'lib/rsruby.rb', line 233

def RSRuby.get_rsruby_showfiles
  @@rsruby_showfiles
end

.set_default_mode(m) ⇒ Object

Sets the default conversion mode for RSRuby. The constants defined in #RSRuby should be used



196
197
198
199
200
201
# File 'lib/rsruby.rb', line 196

def RSRuby.set_default_mode(m)
  if m < -1 or m > TOP_CONVERSION
    raise ArgumentError, "Invalid mode requested"
  end
  @@default_mode = m
end

.set_rsruby_input(m) ⇒ Object

TODO - not implemented



208
209
210
# File 'lib/rsruby.rb', line 208

def RSRuby.set_rsruby_input(m)
  @@rsruby_input = m
end

.set_rsruby_output(m) ⇒ Object

TODO - not implemented



218
219
220
# File 'lib/rsruby.rb', line 218

def RSRuby.set_rsruby_output(m)
  @@rsruby_output = m
end

.set_rsruby_showfiles(m) ⇒ Object

TODO - not implemented



228
229
230
# File 'lib/rsruby.rb', line 228

def RSRuby.set_rsruby_showfiles(m)
  @@rsruby_showfiles = m
end

Instance Method Details

#[](r_id) ⇒ Object

The same as method_missing, but only returns the R function/object, does not call it.



135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/rsruby.rb', line 135

def [](r_id)

  #Translate Ruby method call to R
  robj_name = RSRuby.convert_method_name(r_id.to_s)
  
  #Retrieve it
  robj = self.__getitem__(robj_name)
  
  #And return it
  return robj

end

#__getitem__(name) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/rsruby.rb', line 268

def __getitem__(name)

  #Find the identifier and cache (unless already cached)
  unless @@cache.has_key?(name)
    @@cache[name] = @@cache['get'].lcall([['',name]])
  end

  #Retrieve object from cache
  robj = @@cache[name]

  return robj

end

#c_initializeObject



69
# File 'lib/rsruby.rb', line 69

alias c_initialize initialize

#class_tableObject

Returns the current class table Hash for RSRuby.



238
239
240
# File 'lib/rsruby.rb', line 238

def class_table
  @@class_table
end

#class_table=(h) ⇒ Object

Sets the RSRuby class table Hash.



243
244
245
# File 'lib/rsruby.rb', line 243

def class_table=(h)
  @@class_table = h
end

#eval_R(s) ⇒ Object

Evaluates the given string in R. Returns the result of the evaluation.



258
259
260
# File 'lib/rsruby.rb', line 258

def eval_R(s)
  self.eval(self.parse(:text => s))
end

#get_fun(name) ⇒ Object

Obtain an R object via its name. This is only used to get the ‘get’ function. All subsequent calls go via the ‘get’ function itself



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
# File 'ext/rsruby.c', line 70

VALUE get_fun(VALUE self, VALUE name){

  VALUE str;
  int conversion=TOP_MODE;
  SEXP robj;
  VALUE  rubyobj;
  //VALUE  params[2];
  char* cstr_name;

  str = StringValue(name);

  cstr_name = RSTRING(str)->ptr;

  robj = (SEXP)get_fun_from_name(cstr_name);
  if (!robj)
    return Qnil;

  /* Wrap the returned R object as a ruby Object */
  rubyobj = Data_Wrap_Struct(rb_const_get(rb_cObject, 
					  rb_intern("RObj")), 0, 0, robj);
  rb_iv_set(rubyobj,"@conversion",INT2FIX(conversion));
  rb_iv_set(rubyobj,"@wrap",Qfalse);

  return rubyobj;

}

#help(*args) ⇒ Object

Wraps the R help function.



263
264
265
266
# File 'lib/rsruby.rb', line 263

def help(*args)
  helpobj = @@cache['helpfun'].call(args)
  self.print(helpobj)
end

#proc_tableObject

Returns the current proc table Hash for RSRuby.



248
249
250
# File 'lib/rsruby.rb', line 248

def proc_table
  @@proc_table
end

#proc_table=(h) ⇒ Object

Sets the RSRuby proc table Hash.



253
254
255
# File 'lib/rsruby.rb', line 253

def proc_table=(h)
  @@proc_table = h
end

#shutdownObject

Shutdown the R interpreter



119
120
121
122
123
124
# File 'ext/rsruby.c', line 119

VALUE cShutdown(VALUE self){

  r_finalize();
  return Qtrue;

}

#with_mode(mode, func) ⇒ Object

Takes an #RObj representing an R function and sets the ‘wrapping’ mode for that function. Implemented for compatibility with RPy.



150
151
152
153
# File 'lib/rsruby.rb', line 150

def with_mode(mode,func)
  func.wrap = mode
  return func
end