scicom 0.2.0-java
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/LICENSE.txt +674 -0
- data/README.md +66 -0
- data/README.md~ +290 -0
- data/Rakefile +51 -0
- data/config.rb +163 -0
- data/doc/PypeR.pdf +0 -0
- data/doc/Stat 133 Class Notes (Phil Spector).pdf +29905 -45
- data/doc/The R interface.docx +0 -0
- data/lib/JRubyR/as_mdarray.rb +60 -0
- data/lib/JRubyR/attributes.rb +74 -0
- data/lib/JRubyR/dataframe.rb +35 -0
- data/lib/JRubyR/environment.rb +60 -0
- data/lib/JRubyR/function.rb +61 -0
- data/lib/JRubyR/index.rb +278 -0
- data/lib/JRubyR/list.rb +56 -0
- data/lib/JRubyR/list_orig.rb +111 -0
- data/lib/JRubyR/logical_value.rb +56 -0
- data/lib/JRubyR/rbsexp.rb +386 -0
- data/lib/JRubyR/renjin.rb +431 -0
- data/lib/JRubyR/ruby_classes.rb +58 -0
- data/lib/JRubyR/sequence.rb +56 -0
- data/lib/JRubyR/vector.rb +493 -0
- data/lib/env.rb +12 -0
- data/lib/rinruby.rb +795 -0
- data/lib/scicom.rb +29 -0
- data/target/helper.jar +0 -0
- data/test/baseball.csv +1 -0
- data/test/env.rb +7 -0
- data/test/test_R_interface.rb +165 -0
- data/test/test_array.rb +191 -0
- data/test/test_attributes.rb +261 -0
- data/test/test_basic.rb +156 -0
- data/test/test_column-major.rb +114 -0
- data/test/test_complete.rb +49 -0
- data/test/test_creation.rb +299 -0
- data/test/test_dataframe.rb +248 -0
- data/test/test_distribution.rb +320 -0
- data/test/test_double_assign.rb +240 -0
- data/test/test_double_receive.rb +106 -0
- data/test/test_environment.rb +57 -0
- data/test/test_factor.rb +285 -0
- data/test/test_functions.rb +67 -0
- data/test/test_linear_model.rb +64 -0
- data/test/test_list.rb +220 -0
- data/test/test_matrix.rb +205 -0
- data/test/test_mdarray.rb +258 -0
- data/test/test_operators.rb +227 -0
- data/test/test_sequence.rb +63 -0
- data/test/test_subsetting.rb +67 -0
- data/test/test_tmp.rb +67 -0
- data/test/test_vector.rb +227 -0
- data/vendor/Renjin.pdf +0 -0
- data/vendor/renjin-script-engine-0.7.0-RC7-SNAPSHOT-jar-with-dependencies.jar +0 -0
- data/version.rb +2 -0
- metadata +196 -0
data/lib/env.rb
ADDED
@@ -0,0 +1,12 @@
|
|
1
|
+
require 'java'
|
2
|
+
require_relative '../config.rb'
|
3
|
+
|
4
|
+
$CLASSPATH << "#{File.dirname(__FILE__)}/../vendor/"
|
5
|
+
|
6
|
+
Dir["#{File.dirname(__FILE__)}/../vendor/*.jar"].each do |jar|
|
7
|
+
require jar
|
8
|
+
end
|
9
|
+
|
10
|
+
Dir["#{File.dirname(__FILE__)}/../target/*.jar"].each do |jar|
|
11
|
+
require jar
|
12
|
+
end
|
data/lib/rinruby.rb
ADDED
@@ -0,0 +1,795 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
#=RinRuby: Accessing the R[http://www.r-project.org] interpreter from pure Ruby
|
3
|
+
#
|
4
|
+
#RinRuby is a Ruby library that integrates the R interpreter in Ruby, making R's statistical routines and graphics available within Ruby. The library consists of a single Ruby script that is simple to install and does not require any special compilation or installation of R. Since the library is 100% pure Ruby, it works on a variety of operating systems, Ruby implementations, and versions of R. RinRuby's methods are simple, making for readable code. The {website [rinruby.ddahl.org]}[http://rinruby.ddahl.org] describes RinRuby usage, provides comprehensive documentation, gives several examples, and discusses RinRuby's implementation.
|
5
|
+
#
|
6
|
+
#Below is a simple example of RinRuby usage for simple linear regression. The simulation parameters are defined in Ruby, computations are performed in R, and Ruby reports the results. In a more elaborate application, the simulation parameter might come from input from a graphical user interface, the statistical analysis might be more involved, and the results might be an HTML page or PDF report.
|
7
|
+
#
|
8
|
+
#<b>Code</b>:
|
9
|
+
#
|
10
|
+
# require "rinruby"
|
11
|
+
# n = 10
|
12
|
+
# beta_0 = 1
|
13
|
+
# beta_1 = 0.25
|
14
|
+
# alpha = 0.05
|
15
|
+
# seed = 23423
|
16
|
+
# R.x = (1..n).entries
|
17
|
+
# R.eval <<EOF
|
18
|
+
# set.seed(#{seed})
|
19
|
+
# y <- #{beta_0} + #{beta_1}*x + rnorm(#{n})
|
20
|
+
# fit <- lm( y ~ x )
|
21
|
+
# est <- round(coef(fit),3)
|
22
|
+
# pvalue <- summary(fit)$coefficients[2,4]
|
23
|
+
# EOF
|
24
|
+
# puts "E(y|x) ~= #{R.est[0]} + #{R.est[1]} * x"
|
25
|
+
# if R.pvalue < alpha
|
26
|
+
# puts "Reject the null hypothesis and conclude that x and y are related."
|
27
|
+
# else
|
28
|
+
# puts "There is insufficient evidence to conclude that x and y are related."
|
29
|
+
# end
|
30
|
+
#
|
31
|
+
#<b>Output</b>:
|
32
|
+
#
|
33
|
+
# E(y|x) ~= 1.264 + 0.273 * x
|
34
|
+
# Reject the null hypothesis and conclude that x and y are related.
|
35
|
+
#
|
36
|
+
#Coded by:: David B. Dahl
|
37
|
+
#Documented by:: David B. Dahl & Scott Crawford
|
38
|
+
#Copyright:: 2005-2009
|
39
|
+
#Web page:: http://rinruby.ddahl.org
|
40
|
+
#E-mail:: mailto:rinruby@ddahl.org
|
41
|
+
#License:: GNU Lesser General Public License (LGPL), version 3 or later
|
42
|
+
#
|
43
|
+
#--
|
44
|
+
# This program is free software: you can redistribute it and/or modify
|
45
|
+
# it under the terms of the GNU Lesser General Public License as published by
|
46
|
+
# the Free Software Foundation, either version 3 of the License, or
|
47
|
+
# (at your option) any later version.
|
48
|
+
#
|
49
|
+
# This program is distributed in the hope that it will be useful,
|
50
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
51
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
52
|
+
# GNU General Public License for more details.
|
53
|
+
#
|
54
|
+
# You should have received a copy of the GNU Lesser General Public License
|
55
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>
|
56
|
+
#++
|
57
|
+
#
|
58
|
+
#
|
59
|
+
#The files "java" and "readline" are used when available to add functionality.
|
60
|
+
require 'matrix'
|
61
|
+
class RinRuby
|
62
|
+
|
63
|
+
require 'socket'
|
64
|
+
|
65
|
+
|
66
|
+
VERSION = '2.0.1'
|
67
|
+
|
68
|
+
|
69
|
+
attr_reader :interactive
|
70
|
+
attr_reader :readline
|
71
|
+
# Exception for closed engine
|
72
|
+
EngineClosed=Class.new(Exception)
|
73
|
+
# Parse error
|
74
|
+
ParseError=Class.new(Exception)
|
75
|
+
|
76
|
+
|
77
|
+
#RinRuby is invoked within a Ruby script (or the interactive "irb" prompt denoted >>) using:
|
78
|
+
#
|
79
|
+
# >> require "rinruby"
|
80
|
+
#
|
81
|
+
#The previous statement reads the definition of the RinRuby class into the current Ruby interpreter and creates an instance of the RinRuby class named R. There is a second method for starting an instance of R which allows the user to use any name for the instance, in this case myr:
|
82
|
+
#
|
83
|
+
# >> require "rinruby"
|
84
|
+
# >> myr = RinRuby.new
|
85
|
+
# >> myr.eval "rnorm(1)"
|
86
|
+
#
|
87
|
+
#Any number of independent instances of R can be created in this way.
|
88
|
+
#
|
89
|
+
#<b>Parameters that can be passed to the new method using a Hash:</b>
|
90
|
+
#
|
91
|
+
#* :echo: By setting the echo to false, output from R is suppressed, although warnings are still printed. This option can be changed later by using the echo method. The default is true.
|
92
|
+
#* :interactive: When interactive is false, R is run in non-interactive mode, resulting in plots without an explicit device being written to Rplots.pdf. Otherwise (i.e., interactive is true), plots are shown on the screen. The default is true.
|
93
|
+
#* :executable: The path of the R executable (which is "R" in Linux and Mac OS X, or "Rterm.exe" in Windows) can be set with the executable argument. The default is nil which makes RinRuby use the registry keys to find the path (on Windows) or use the path defined by $PATH (on Linux and Mac OS X).
|
94
|
+
#* :port_number: This is the smallest port number on the local host that could be used to pass data between Ruby and R. The actual port number used depends on port_width.
|
95
|
+
#* :port_width: RinRuby will randomly select a uniform number between port_number and port_number + port_width - 1 (inclusive) to pass data between Ruby and R. If the randomly selected port is not available, RinRuby will continue selecting random ports until it finds one that is available. By setting port_width to 1, RinRuby will wait until port_number is available. The default port_width is 1000.
|
96
|
+
#
|
97
|
+
#It may be desirable to change the parameters to the instance of R, but still call it by the name of R. In that case the old instance of R which was created with the 'require "rinruby"' statement should be closed first using the quit method which is explained below. Unless the previous instance is killed, it will continue to use system resources until exiting Ruby. The following shows an example by changing the parameter echo:
|
98
|
+
#
|
99
|
+
# >> require "rinruby"
|
100
|
+
# >> R.quit
|
101
|
+
# >> R = RinRuby.new(false)
|
102
|
+
attr_reader :echo_enabled
|
103
|
+
attr_reader :executable
|
104
|
+
attr_reader :port_number
|
105
|
+
attr_reader :port_width
|
106
|
+
attr_reader :hostname
|
107
|
+
|
108
|
+
def initialize(*args)
|
109
|
+
opts=Hash.new
|
110
|
+
if args.size==1 and args[0].is_a? Hash
|
111
|
+
opts=args[0]
|
112
|
+
else
|
113
|
+
opts[:echo]=args.shift unless args.size==0
|
114
|
+
opts[:interactive]=args.shift unless args.size==0
|
115
|
+
opts[:executable]=args.shift unless args.size==0
|
116
|
+
opts[:port_number]=args.shift unless args.size==0
|
117
|
+
opts[:port_width]=args.shift unless args.size==0
|
118
|
+
end
|
119
|
+
default_opts= {:echo=>true, :interactive=>true, :executable=>nil, :port_number=>38442, :port_width=>1000, :hostname=>'127.0.0.1'}
|
120
|
+
|
121
|
+
@opts=default_opts.merge(opts)
|
122
|
+
@port_width=@opts[:port_width]
|
123
|
+
@executable=@opts[:executable]
|
124
|
+
@hostname=@opts[:hostname]
|
125
|
+
while true
|
126
|
+
begin
|
127
|
+
@port_number = @opts[:port_number] + rand(port_width)
|
128
|
+
@server_socket = TCPServer::new(@hostname, @port_number)
|
129
|
+
break
|
130
|
+
rescue Errno::EADDRINUSE
|
131
|
+
sleep 0.5 if port_width == 1
|
132
|
+
end
|
133
|
+
end
|
134
|
+
@echo_enabled = @opts[:echo]
|
135
|
+
@echo_stderr = false
|
136
|
+
@interactive = @opts[:interactive]
|
137
|
+
@platform = case RUBY_PLATFORM
|
138
|
+
when /mswin/ then 'windows'
|
139
|
+
when /mingw/ then 'windows'
|
140
|
+
when /bccwin/ then 'windows'
|
141
|
+
when /cygwin/ then 'windows-cygwin'
|
142
|
+
when /java/
|
143
|
+
require 'java' #:nodoc:
|
144
|
+
if java.lang.System.getProperty("os.name") =~ /[Ww]indows/
|
145
|
+
'windows-java'
|
146
|
+
else
|
147
|
+
'default-java'
|
148
|
+
end
|
149
|
+
else 'default'
|
150
|
+
end
|
151
|
+
if @executable == nil
|
152
|
+
@executable = ( @platform =~ /windows/ ) ? find_R_on_windows(@platform =~ /cygwin/) : 'R'
|
153
|
+
end
|
154
|
+
platform_options = []
|
155
|
+
if ( @interactive )
|
156
|
+
begin
|
157
|
+
require 'readline'
|
158
|
+
rescue LoadError
|
159
|
+
end
|
160
|
+
@readline = defined?(Readline)
|
161
|
+
platform_options << ( ( @platform =~ /windows/ ) ? '--ess' : '--interactive' )
|
162
|
+
else
|
163
|
+
@readline = false
|
164
|
+
end
|
165
|
+
cmd = %Q<#{executable} #{platform_options.join(' ')} --slave>
|
166
|
+
@engine = IO.popen(cmd,"w+")
|
167
|
+
@reader = @engine
|
168
|
+
@writer = @engine
|
169
|
+
raise "Engine closed" if @engine.closed?
|
170
|
+
@writer.puts <<-EOF
|
171
|
+
#{RinRuby_KeepTrying_Variable} <- TRUE
|
172
|
+
while ( #{RinRuby_KeepTrying_Variable} ) {
|
173
|
+
#{RinRuby_Socket} <- try(suppressWarnings(socketConnection("#{@hostname}", #{@port_number}, blocking=TRUE, open="rb")),TRUE)
|
174
|
+
if ( inherits(#{RinRuby_Socket},"try-error") ) {
|
175
|
+
Sys.sleep(0.1)
|
176
|
+
} else {
|
177
|
+
#{RinRuby_KeepTrying_Variable} <- FALSE
|
178
|
+
}
|
179
|
+
}
|
180
|
+
rm(#{RinRuby_KeepTrying_Variable})
|
181
|
+
EOF
|
182
|
+
r_rinruby_get_value
|
183
|
+
r_rinruby_pull
|
184
|
+
r_rinruby_parseable
|
185
|
+
@socket = @server_socket.accept
|
186
|
+
echo(nil,true) if @platform =~ /.*-java/ # Redirect error messages on the Java platform
|
187
|
+
end
|
188
|
+
|
189
|
+
#The quit method will properly close the bridge between Ruby and R, freeing up system resources. This method does not need to be run when a Ruby script ends.
|
190
|
+
|
191
|
+
def quit
|
192
|
+
begin
|
193
|
+
@writer.puts "q(save='no')"
|
194
|
+
# TODO: Verify if read is needed
|
195
|
+
@socket.read()
|
196
|
+
#@socket.close
|
197
|
+
@engine.close
|
198
|
+
|
199
|
+
|
200
|
+
@server_socket.close
|
201
|
+
#@reader.close
|
202
|
+
#@writer.close
|
203
|
+
true
|
204
|
+
ensure
|
205
|
+
@engine.close unless @engine.closed?
|
206
|
+
@server_socket.close unless @server_socket.closed?
|
207
|
+
end
|
208
|
+
end
|
209
|
+
|
210
|
+
|
211
|
+
#The eval instance method passes the R commands contained in the supplied string and displays any resulting plots or prints the output. For example:
|
212
|
+
#
|
213
|
+
# >> sample_size = 10
|
214
|
+
# >> R.eval "x <- rnorm(#{sample_size})"
|
215
|
+
# >> R.eval "summary(x)"
|
216
|
+
# >> R.eval "sd(x)"
|
217
|
+
#
|
218
|
+
#produces the following:
|
219
|
+
#
|
220
|
+
# Min. 1st Qu. Median Mean 3rd Qu. Max.
|
221
|
+
# -1.88900 -0.84930 -0.45220 -0.49290 -0.06069 0.78160
|
222
|
+
# [1] 0.7327981
|
223
|
+
#
|
224
|
+
#This example used a string substitution to make the argument to first eval method equivalent to x <- rnorm(10). This example used three invocations of the eval method, but a single invoke is possible using a here document:
|
225
|
+
#
|
226
|
+
# >> R.eval <<EOF
|
227
|
+
# x <- rnorm(#{sample_size})
|
228
|
+
# summary(x)
|
229
|
+
# sd(x)
|
230
|
+
# EOF
|
231
|
+
#
|
232
|
+
#<b>Parameters that can be passed to the eval method</b>
|
233
|
+
#
|
234
|
+
#* string: The string parameter is the code which is to be passed to R, for example, string = "hist(gamma(1000,5,3))". The string can also span several lines of code by use of a here document, as shown:
|
235
|
+
# R.eval <<EOF
|
236
|
+
# x<-rgamma(1000,5,3)
|
237
|
+
# hist(x)
|
238
|
+
# EOF
|
239
|
+
#
|
240
|
+
#* echo_override: This argument allows one to set the echo behavior for this call only. The default for echo_override is nil, which does not override the current echo behavior.
|
241
|
+
|
242
|
+
def eval(string, echo_override=nil)
|
243
|
+
raise EngineClosed if @engine.closed?
|
244
|
+
echo_enabled = ( echo_override != nil ) ? echo_override : @echo_enabled
|
245
|
+
if complete?(string)
|
246
|
+
@writer.puts string
|
247
|
+
@writer.puts "warning('#{RinRuby_Stderr_Flag}',immediate.=TRUE)" if @echo_stderr
|
248
|
+
@writer.puts "print('#{RinRuby_Eval_Flag}')"
|
249
|
+
else
|
250
|
+
raise ParseError, "Parse error on eval:#{string}"
|
251
|
+
end
|
252
|
+
Signal.trap('INT') do
|
253
|
+
@writer.print ''
|
254
|
+
@reader.gets if @platform !~ /java/
|
255
|
+
Signal.trap('INT') do
|
256
|
+
end
|
257
|
+
return true
|
258
|
+
end
|
259
|
+
found_eval_flag = false
|
260
|
+
found_stderr_flag = false
|
261
|
+
while true
|
262
|
+
echo_eligible = true
|
263
|
+
begin
|
264
|
+
line = @reader.gets
|
265
|
+
rescue
|
266
|
+
return false
|
267
|
+
end
|
268
|
+
if ! line
|
269
|
+
return false
|
270
|
+
end
|
271
|
+
while line.chomp!
|
272
|
+
end
|
273
|
+
line = line[8..-1] if line[0] == 27 # Delete escape sequence
|
274
|
+
if line == "[1] \"#{RinRuby_Eval_Flag}\""
|
275
|
+
found_eval_flag = true
|
276
|
+
echo_eligible = false
|
277
|
+
end
|
278
|
+
if line == "Warning: #{RinRuby_Stderr_Flag}"
|
279
|
+
found_stderr_flag = true
|
280
|
+
echo_eligible = false
|
281
|
+
end
|
282
|
+
break if found_eval_flag && ( found_stderr_flag == @echo_stderr )
|
283
|
+
return false if line == RinRuby_Exit_Flag
|
284
|
+
if echo_enabled && echo_eligible
|
285
|
+
puts line
|
286
|
+
$stdout.flush if @platform !~ /windows/
|
287
|
+
end
|
288
|
+
end
|
289
|
+
Signal.trap('INT') do
|
290
|
+
end
|
291
|
+
true
|
292
|
+
end
|
293
|
+
|
294
|
+
#When sending code to Ruby using an interactive prompt, this method will change the prompt to an R prompt. From the R prompt commands can be sent to R exactly as if the R program was actually running. When the user is ready to return to Ruby, then the command exit() will return the prompt to Ruby. This is the ideal situation for the explorative programmer who needs to run several lines of code in R, and see the results after each command. This is also an easy way to execute loops without the use of a here document. It should be noted that the prompt command does not work in a script, just Ruby's interactive irb.
|
295
|
+
#
|
296
|
+
#<b>Parameters that can be passed to the prompt method:</b>
|
297
|
+
#
|
298
|
+
#* regular_prompt: This defines the string used to denote the R prompt.
|
299
|
+
#
|
300
|
+
#* continue_prompt: This is the string used to denote R's prompt for an incomplete statement (such as a multiple for loop).
|
301
|
+
|
302
|
+
def prompt(regular_prompt="> ", continue_prompt="+ ")
|
303
|
+
raise "The 'prompt' method only available in 'interactive' mode" if ! @interactive
|
304
|
+
return false if ! eval("0",false)
|
305
|
+
prompt = regular_prompt
|
306
|
+
while true
|
307
|
+
cmds = []
|
308
|
+
while true
|
309
|
+
if @readline && @interactive
|
310
|
+
cmd = Readline.readline(prompt,true)
|
311
|
+
else
|
312
|
+
print prompt
|
313
|
+
$stdout.flush
|
314
|
+
cmd = gets.strip
|
315
|
+
end
|
316
|
+
cmds << cmd
|
317
|
+
begin
|
318
|
+
if complete?(cmds.join("\n"))
|
319
|
+
prompt = regular_prompt
|
320
|
+
break
|
321
|
+
else
|
322
|
+
prompt = continue_prompt
|
323
|
+
end
|
324
|
+
rescue
|
325
|
+
puts "Parse error"
|
326
|
+
prompt = regular_prompt
|
327
|
+
cmds = []
|
328
|
+
break
|
329
|
+
end
|
330
|
+
end
|
331
|
+
next if cmds.length == 0
|
332
|
+
break if cmds.length == 1 && cmds[0] == "exit()"
|
333
|
+
break if ! eval(cmds.join("\n"),true)
|
334
|
+
end
|
335
|
+
true
|
336
|
+
end
|
337
|
+
|
338
|
+
#If a method is called which is not defined, then it is assumed that the user is attempting to either pull or assign a variable to R. This allows for the short-hand equivalents to the pull and assign methods. For example:
|
339
|
+
#
|
340
|
+
# >> R.x = 2
|
341
|
+
#
|
342
|
+
#is the same as:
|
343
|
+
#
|
344
|
+
# >> R.assign("x",2)
|
345
|
+
#
|
346
|
+
#Also:
|
347
|
+
#
|
348
|
+
# >> n = R.x
|
349
|
+
#
|
350
|
+
#is the same as:
|
351
|
+
#
|
352
|
+
# >> n = R.pull("x")
|
353
|
+
#
|
354
|
+
#The parameters passed to method_missing are those used for the pull or assign depending on the context.
|
355
|
+
|
356
|
+
def method_missing(symbol, *args)
|
357
|
+
name = symbol.id2name
|
358
|
+
if name =~ /(.*)=$/
|
359
|
+
raise ArgumentError, "You shouldn't assign nil" if args==[nil]
|
360
|
+
super if args.length != 1
|
361
|
+
assign($1,args[0])
|
362
|
+
else
|
363
|
+
super if args.length != 0
|
364
|
+
pull(name)
|
365
|
+
end
|
366
|
+
end
|
367
|
+
|
368
|
+
#Data is copied from Ruby to R using the assign method or a short-hand equivalent. For example:
|
369
|
+
#
|
370
|
+
# >> names = ["Lisa","Teasha","Aaron","Thomas"]
|
371
|
+
# >> R.assign "people", names
|
372
|
+
# >> R.eval "sort(people)"
|
373
|
+
#
|
374
|
+
#produces the following :
|
375
|
+
#
|
376
|
+
# [1] "Aaron" "Lisa" "Teasha" "Thomas"
|
377
|
+
#
|
378
|
+
#The short-hand equivalent to the assign method is simply:
|
379
|
+
#
|
380
|
+
# >> R.people = names
|
381
|
+
#
|
382
|
+
#Some care is needed when using the short-hand of the assign method since the label (i.e., people in this case) must be a valid method name in Ruby. For example, R.copy.of.names = names will not work, but R.copy_of_names = names is permissible.
|
383
|
+
#
|
384
|
+
#The assign method supports Ruby variables of type Fixnum (i.e., integer), Bignum (i.e., integer), Float (i.e., double), String, and arrays of one of those three fundamental types. Note that Fixnum or Bignum values that exceed the capacity of R's integers are silently converted to doubles. Data in other formats must be coerced when copying to R.
|
385
|
+
#
|
386
|
+
#<b>Parameters that can be passed to the assign method:</b>
|
387
|
+
#
|
388
|
+
#* name: The name of the variable desired in R.
|
389
|
+
#
|
390
|
+
#* value: The value the R variable should have. The assign method supports Ruby variables of type Fixnum (i.e., integer), Bignum (i.e., integer), Float (i.e., double), String, and arrays of one of those three fundamental types. Note that Fixnum or Bignum values that exceed the capacity of R's integers are silently converted to doubles. Data in other formats must be coerced when copying to R.
|
391
|
+
#
|
392
|
+
#The assign method is an alternative to the simplified method, with some additional flexibility. When using the simplified method, the parameters of name and value are automatically used, in other words:
|
393
|
+
#
|
394
|
+
# >> R.test = 144
|
395
|
+
#
|
396
|
+
#is the same as:
|
397
|
+
#
|
398
|
+
# >> R.assign("test",144)
|
399
|
+
#
|
400
|
+
#Of course it would be confusing to use the shorthand notation to assign a variable named eval, echo, or any other already defined function. RinRuby would assume you were calling the function, rather than trying to assign a variable.
|
401
|
+
#
|
402
|
+
#When assigning an array containing differing types of variables, RinRuby will follow R’s conversion conventions. An array that contains any Strings will result in a character vector in R. If the array does not contain any Strings, but it does contain a Float or a large integer (in absolute value), then the result will be a numeric vector of Doubles in R. If there are only integers that are suffciently small (in absolute value), then the result will be a numeric vector of integers in R.
|
403
|
+
|
404
|
+
def assign(name, value)
|
405
|
+
raise EngineClosed if @engine.closed?
|
406
|
+
if assignable?(name)
|
407
|
+
assign_engine(name,value)
|
408
|
+
else
|
409
|
+
raise ParseError, "Parse error"
|
410
|
+
end
|
411
|
+
end
|
412
|
+
|
413
|
+
#Data is copied from R to Ruby using the pull method or a short-hand equivalent. The R object x defined with an eval method can be copied to Ruby object copy_of_x as follows:
|
414
|
+
#
|
415
|
+
# >> R.eval "x <- rnorm(10)"
|
416
|
+
# >> copy_of_x = R.pull "x"
|
417
|
+
# >> puts copy_of_x
|
418
|
+
#
|
419
|
+
#which produces the following :
|
420
|
+
#
|
421
|
+
# -0.376404489256671
|
422
|
+
# -1.0759798269397
|
423
|
+
# -0.494240140140996
|
424
|
+
# 0.131171385795721
|
425
|
+
# -0.878328334369391
|
426
|
+
# -0.762290423047929
|
427
|
+
# -0.410227216105828
|
428
|
+
# 0.0445512804225151
|
429
|
+
# -1.88887454545995
|
430
|
+
# 0.781602719849499
|
431
|
+
#
|
432
|
+
#RinRuby also supports a convenient short-hand notation when the argument to pull is simply a previously-defined R object (whose name conforms to Ruby's requirements for method names). For example:
|
433
|
+
#
|
434
|
+
# >> copy_of_x = R.x
|
435
|
+
#
|
436
|
+
#The explicit assign method, however, can take an arbitrary R statement. For example:
|
437
|
+
#
|
438
|
+
# >> summary_of_x = R.pull "as.numeric(summary(x))"
|
439
|
+
# >> puts summary_of_x
|
440
|
+
#
|
441
|
+
#produces the following:
|
442
|
+
#
|
443
|
+
# -1.889
|
444
|
+
# -0.8493
|
445
|
+
# -0.4522
|
446
|
+
# -0.4929
|
447
|
+
# -0.06069
|
448
|
+
# 0.7816
|
449
|
+
#
|
450
|
+
#Notice the use above of the as.numeric function in R. This is necessary since the pull method only supports R vectors which are numeric (i.e., integers or doubles) and character (i.e., strings). Data in other formats must be coerced when copying to Ruby.
|
451
|
+
#
|
452
|
+
#<b>Parameters that can be passed to the pull method:</b>
|
453
|
+
#
|
454
|
+
#* string: The name of the variable that should be pulled from R. The pull method only supports R vectors which are numeric (i.e., integers or doubles) or character (i.e., strings). The R value of NA is pulled as nil into Ruby. Data in other formats must be coerced when copying to Ruby.
|
455
|
+
#
|
456
|
+
#* singletons: R represents a single number as a vector of length one, but in Ruby it is often more convenient to use a number rather than an array of length one. Setting singleton=false will cause the pull method to shed the array, while singletons=true will return the number of string within an array. The default is false.
|
457
|
+
#
|
458
|
+
#The pull method is an alternative to the simplified form where the parameters are automatically used. For example:
|
459
|
+
#
|
460
|
+
# >> puts R.test
|
461
|
+
#
|
462
|
+
#is the same as:
|
463
|
+
#
|
464
|
+
# >> puts R.pull("test")
|
465
|
+
|
466
|
+
def pull(string, singletons=false)
|
467
|
+
raise EngineClosed if @engine.closed?
|
468
|
+
if complete?(string)
|
469
|
+
result = pull_engine(string)
|
470
|
+
if ( ! singletons ) && ( result.length == 1 ) && ( result.class != String )
|
471
|
+
result = result[0]
|
472
|
+
end
|
473
|
+
result
|
474
|
+
else
|
475
|
+
raise ParseError, "Parse error"
|
476
|
+
end
|
477
|
+
end
|
478
|
+
|
479
|
+
#The echo method controls whether the eval method displays output from R and, if echo is enabled, whether messages, warnings, and errors from stderr are also displayed.
|
480
|
+
#
|
481
|
+
#<b>Parameters that can be passed to the eval method</b>
|
482
|
+
#
|
483
|
+
#* enable: Setting enable to false will turn all output off until the echo command is used again with enable equal to true. The default is nil, which will return the current setting.
|
484
|
+
#
|
485
|
+
#* stderr: Setting stderr to true will force messages, warnings, and errors from R to be routed through stdout. Using stderr redirection is typically not needed for the C implementation of Ruby and is thus not not enabled by default for this implementation. It is typically necessary for jRuby and is enabled by default in this case. This redirection works well in practice but it can lead to interleaving output which may confuse RinRuby. In such cases, stderr redirection should not be used. Echoing must be enabled when using stderr redirection.
|
486
|
+
|
487
|
+
def echo(enable=nil,stderr=nil)
|
488
|
+
if ( enable == false ) && ( stderr == true )
|
489
|
+
raise "You can only redirect stderr if you are echoing is enabled."
|
490
|
+
end
|
491
|
+
if ( enable != nil ) && ( enable != @echo_enabled )
|
492
|
+
echo(nil,false) if ! enable
|
493
|
+
@echo_enabled = ! @echo_enabled
|
494
|
+
end
|
495
|
+
if @echo_enabled && ( stderr != nil ) && ( stderr != @echo_stderr )
|
496
|
+
@echo_stderr = ! @echo_stderr
|
497
|
+
if @echo_stderr
|
498
|
+
eval "sink(stdout(),type='message')"
|
499
|
+
else
|
500
|
+
eval "sink(type='message')"
|
501
|
+
end
|
502
|
+
end
|
503
|
+
[ @echo_enabled, @echo_stderr ]
|
504
|
+
end
|
505
|
+
|
506
|
+
private
|
507
|
+
|
508
|
+
#:stopdoc:
|
509
|
+
RinRuby_Type_NotFound = -2
|
510
|
+
RinRuby_Type_Unknown = -1
|
511
|
+
RinRuby_Type_Double = 0
|
512
|
+
RinRuby_Type_Integer = 1
|
513
|
+
RinRuby_Type_String = 2
|
514
|
+
RinRuby_Type_String_Array = 3
|
515
|
+
RinRuby_Type_Matrix = 4
|
516
|
+
|
517
|
+
RinRuby_KeepTrying_Variable = ".RINRUBY.KEEPTRYING.VARIABLE"
|
518
|
+
RinRuby_Length_Variable = ".RINRUBY.PULL.LENGTH.VARIABLE"
|
519
|
+
RinRuby_Type_Variable = ".RINRUBY.PULL.TYPE.VARIABLE"
|
520
|
+
RinRuby_Socket = ".RINRUBY.PULL.SOCKET"
|
521
|
+
RinRuby_Variable = ".RINRUBY.PULL.VARIABLE"
|
522
|
+
RinRuby_Parse_String = ".RINRUBY.PARSE.STRING"
|
523
|
+
RinRuby_Eval_Flag = "RINRUBY.EVAL.FLAG"
|
524
|
+
RinRuby_Stderr_Flag = "RINRUBY.STDERR.FLAG"
|
525
|
+
RinRuby_Exit_Flag = "RINRUBY.EXIT.FLAG"
|
526
|
+
RinRuby_Max_Unsigned_Integer = 2**32
|
527
|
+
RinRuby_Half_Max_Unsigned_Integer = 2**31
|
528
|
+
RinRuby_NA_R_Integer = 2**31
|
529
|
+
RinRuby_Max_R_Integer = 2**31-1
|
530
|
+
RinRuby_Min_R_Integer = -2**31+1
|
531
|
+
#:startdoc:
|
532
|
+
|
533
|
+
|
534
|
+
def r_rinruby_parseable
|
535
|
+
@writer.puts <<-EOF
|
536
|
+
rinruby_parseable<-function(var) {
|
537
|
+
result=try(parse(text=var),TRUE)
|
538
|
+
if(inherits(result, "try-error")) {
|
539
|
+
writeBin(as.integer(-1),#{RinRuby_Socket}, endian="big")
|
540
|
+
} else {
|
541
|
+
writeBin(as.integer(1),#{RinRuby_Socket}, endian="big")
|
542
|
+
}
|
543
|
+
}
|
544
|
+
EOF
|
545
|
+
end
|
546
|
+
# Create function on ruby to get values
|
547
|
+
def r_rinruby_get_value
|
548
|
+
@writer.puts <<-EOF
|
549
|
+
rinruby_get_value <-function() {
|
550
|
+
value <- NULL
|
551
|
+
type <- readBin(#{RinRuby_Socket}, integer(), 1, endian="big")
|
552
|
+
length <- readBin(#{RinRuby_Socket},integer(),1,endian="big")
|
553
|
+
if ( type == #{RinRuby_Type_Double} ) {
|
554
|
+
value <- readBin(#{RinRuby_Socket},numeric(), length,endian="big")
|
555
|
+
} else if ( type == #{RinRuby_Type_Integer} ) {
|
556
|
+
value <- readBin(#{RinRuby_Socket},integer(), length, endian="big")
|
557
|
+
} else if ( type == #{RinRuby_Type_String} ) {
|
558
|
+
value <- readBin(#{RinRuby_Socket},character(),1,endian="big")
|
559
|
+
} else {
|
560
|
+
value <-NULL
|
561
|
+
}
|
562
|
+
value
|
563
|
+
}
|
564
|
+
EOF
|
565
|
+
end
|
566
|
+
|
567
|
+
def r_rinruby_pull
|
568
|
+
@writer.puts <<-EOF
|
569
|
+
rinruby_pull <-function(var)
|
570
|
+
{
|
571
|
+
if ( inherits(var ,"try-error") ) {
|
572
|
+
writeBin(as.integer(#{RinRuby_Type_NotFound}),#{RinRuby_Socket},endian="big")
|
573
|
+
} else {
|
574
|
+
if (is.matrix(var)) {
|
575
|
+
writeBin(as.integer(#{RinRuby_Type_Matrix}),#{RinRuby_Socket},endian="big")
|
576
|
+
writeBin(as.integer(dim(var)[1]),#{RinRuby_Socket},endian="big")
|
577
|
+
writeBin(as.integer(dim(var)[2]),#{RinRuby_Socket},endian="big")
|
578
|
+
|
579
|
+
} else if ( is.double(var) ) {
|
580
|
+
writeBin(as.integer(#{RinRuby_Type_Double}),#{RinRuby_Socket},endian="big")
|
581
|
+
writeBin(as.integer(length(var)),#{RinRuby_Socket},endian="big")
|
582
|
+
writeBin(var,#{RinRuby_Socket},endian="big")
|
583
|
+
} else if ( is.integer(var) ) {
|
584
|
+
writeBin(as.integer(#{RinRuby_Type_Integer}),#{RinRuby_Socket},endian="big")
|
585
|
+
writeBin(as.integer(length(var)),#{RinRuby_Socket},endian="big")
|
586
|
+
writeBin(var,#{RinRuby_Socket},endian="big")
|
587
|
+
} else if ( is.character(var) && ( length(var) == 1 ) ) {
|
588
|
+
writeBin(as.integer(#{RinRuby_Type_String}),#{RinRuby_Socket},endian="big")
|
589
|
+
writeBin(as.integer(nchar(var)),#{RinRuby_Socket},endian="big")
|
590
|
+
writeBin(var,#{RinRuby_Socket},endian="big")
|
591
|
+
} else if ( is.character(var) && ( length(var) > 1 ) ) {
|
592
|
+
writeBin(as.integer(#{RinRuby_Type_String_Array}),#{RinRuby_Socket},endian="big")
|
593
|
+
writeBin(as.integer(length(var)),#{RinRuby_Socket},endian="big")
|
594
|
+
} else {
|
595
|
+
writeBin(as.integer(#{RinRuby_Type_Unknown}),#{RinRuby_Socket},endian="big")
|
596
|
+
}
|
597
|
+
}
|
598
|
+
}
|
599
|
+
EOF
|
600
|
+
|
601
|
+
|
602
|
+
end
|
603
|
+
def to_signed_int(y)
|
604
|
+
if y.kind_of?(Integer)
|
605
|
+
( y > RinRuby_Half_Max_Unsigned_Integer ) ? -(RinRuby_Max_Unsigned_Integer-y) : ( y == RinRuby_NA_R_Integer ? nil : y )
|
606
|
+
else
|
607
|
+
y.collect { |x| ( x > RinRuby_Half_Max_Unsigned_Integer ) ? -(RinRuby_Max_Unsigned_Integer-x) : ( x == RinRuby_NA_R_Integer ? nil : x ) }
|
608
|
+
end
|
609
|
+
end
|
610
|
+
|
611
|
+
def assign_engine(name, value)
|
612
|
+
original_value = value
|
613
|
+
# Special assign for matrixes
|
614
|
+
if value.kind_of?(::Matrix)
|
615
|
+
values=value.row_size.times.collect {|i| value.column_size.times.collect {|j| value[i,j]}}.flatten
|
616
|
+
eval "#{name}=matrix(c(#{values.join(',')}), #{value.row_size}, #{value.column_size}, TRUE)"
|
617
|
+
return original_value
|
618
|
+
end
|
619
|
+
|
620
|
+
if value.kind_of?(String)
|
621
|
+
type = RinRuby_Type_String
|
622
|
+
length = 1
|
623
|
+
elsif value.kind_of?(Integer)
|
624
|
+
if ( value >= RinRuby_Min_R_Integer ) && ( value <= RinRuby_Max_R_Integer )
|
625
|
+
value = [ value.to_i ]
|
626
|
+
type = RinRuby_Type_Integer
|
627
|
+
else
|
628
|
+
value = [ value.to_f ]
|
629
|
+
type = RinRuby_Type_Double
|
630
|
+
end
|
631
|
+
length = 1
|
632
|
+
elsif value.kind_of?(Float)
|
633
|
+
value = [ value.to_f ]
|
634
|
+
type = RinRuby_Type_Double
|
635
|
+
length = 1
|
636
|
+
elsif value.kind_of?(Array)
|
637
|
+
begin
|
638
|
+
if value.any? { |x| x.kind_of?(String) }
|
639
|
+
eval "#{name} <- character(#{value.length})"
|
640
|
+
for index in 0...value.length
|
641
|
+
assign_engine("#{name}[#{index}+1]",value[index])
|
642
|
+
end
|
643
|
+
return original_value
|
644
|
+
elsif value.any? { |x| x.kind_of?(Float) }
|
645
|
+
type = RinRuby_Type_Double
|
646
|
+
value = value.collect { |x| x.to_f }
|
647
|
+
elsif value.all? { |x| x.kind_of?(Integer) }
|
648
|
+
if value.all? { |x| ( x >= RinRuby_Min_R_Integer ) && ( x <= RinRuby_Max_R_Integer ) }
|
649
|
+
type = RinRuby_Type_Integer
|
650
|
+
else
|
651
|
+
value = value.collect { |x| x.to_f }
|
652
|
+
type = RinRuby_Type_Double
|
653
|
+
end
|
654
|
+
else
|
655
|
+
raise "Unsupported data type on Ruby's end"
|
656
|
+
end
|
657
|
+
rescue
|
658
|
+
raise "Unsupported data type on Ruby's end"
|
659
|
+
end
|
660
|
+
length = value.length
|
661
|
+
else
|
662
|
+
raise "Unsupported data type on Ruby's end"
|
663
|
+
end
|
664
|
+
@writer.puts "#{name} <- rinruby_get_value()"
|
665
|
+
|
666
|
+
@socket.write([type,length].pack('NN'))
|
667
|
+
if ( type == RinRuby_Type_String )
|
668
|
+
@socket.write(value)
|
669
|
+
@socket.write([0].pack('C')) # zero-terminated strings
|
670
|
+
else
|
671
|
+
@socket.write(value.pack( ( type==RinRuby_Type_Double ? 'G' : 'N' )*length ))
|
672
|
+
end
|
673
|
+
original_value
|
674
|
+
end
|
675
|
+
|
676
|
+
def pull_engine(string)
|
677
|
+
@writer.puts <<-EOF
|
678
|
+
rinruby_pull(try(#{string}))
|
679
|
+
EOF
|
680
|
+
|
681
|
+
buffer = ""
|
682
|
+
@socket.read(4,buffer)
|
683
|
+
type = to_signed_int(buffer.unpack('N')[0].to_i)
|
684
|
+
if ( type == RinRuby_Type_Unknown )
|
685
|
+
raise "Unsupported data type on R's end"
|
686
|
+
end
|
687
|
+
if ( type == RinRuby_Type_NotFound )
|
688
|
+
return nil
|
689
|
+
end
|
690
|
+
@socket.read(4,buffer)
|
691
|
+
length = to_signed_int(buffer.unpack('N')[0].to_i)
|
692
|
+
|
693
|
+
if ( type == RinRuby_Type_Double )
|
694
|
+
@socket.read(8*length,buffer)
|
695
|
+
result = buffer.unpack('G'*length)
|
696
|
+
elsif ( type == RinRuby_Type_Integer )
|
697
|
+
@socket.read(4*length,buffer)
|
698
|
+
result = to_signed_int(buffer.unpack('N'*length))
|
699
|
+
elsif ( type == RinRuby_Type_String )
|
700
|
+
@socket.read(length,buffer)
|
701
|
+
result = buffer.dup
|
702
|
+
@socket.read(1,buffer) # zero-terminated string
|
703
|
+
result
|
704
|
+
elsif ( type == RinRuby_Type_String_Array )
|
705
|
+
result = Array.new(length,'')
|
706
|
+
for index in 0...length
|
707
|
+
result[index] = pull "#{string}[#{index+1}]"
|
708
|
+
end
|
709
|
+
elsif (type == RinRuby_Type_Matrix)
|
710
|
+
rows=length
|
711
|
+
@socket.read(4,buffer)
|
712
|
+
cols = to_signed_int(buffer.unpack('N')[0].to_i)
|
713
|
+
elements=pull "as.vector(#{string})"
|
714
|
+
index=0
|
715
|
+
result=Matrix.rows(rows.times.collect {|i|
|
716
|
+
cols.times.collect {|j|
|
717
|
+
elements[(j*rows)+i]
|
718
|
+
}
|
719
|
+
})
|
720
|
+
def result.length; 2;end
|
721
|
+
else
|
722
|
+
raise "Unsupported data type on Ruby's end"
|
723
|
+
end
|
724
|
+
result
|
725
|
+
end
|
726
|
+
|
727
|
+
def complete?(string)
|
728
|
+
assign_engine(RinRuby_Parse_String, string)
|
729
|
+
@writer.puts "rinruby_parseable(#{RinRuby_Parse_String})"
|
730
|
+
buffer=""
|
731
|
+
@socket.read(4,buffer)
|
732
|
+
@writer.puts "rm(#{RinRuby_Parse_String})"
|
733
|
+
result = to_signed_int(buffer.unpack('N')[0].to_i)
|
734
|
+
return result==-1 ? false : true
|
735
|
+
|
736
|
+
=begin
|
737
|
+
|
738
|
+
result = pull_engine("unlist(lapply(c('.*','^Error in parse.*','^Error in parse.*unexpected end of input.*'),
|
739
|
+
grep,try({parse(text=#{RinRuby_Parse_String}); 1}, silent=TRUE)))")
|
740
|
+
|
741
|
+
return true if result.length == 1
|
742
|
+
return false if result.length == 3
|
743
|
+
raise ParseError, "Parse error"
|
744
|
+
=end
|
745
|
+
end
|
746
|
+
|
747
|
+
public :complete?
|
748
|
+
|
749
|
+
def assignable?(string)
|
750
|
+
raise ParseError, "Parse error" if ! complete?(string)
|
751
|
+
assign_engine(RinRuby_Parse_String,string)
|
752
|
+
result = pull_engine("as.integer(ifelse(inherits(try({eval(parse(text=paste(#{RinRuby_Parse_String},'<- 1')))}, silent=TRUE),'try-error'),1,0))")
|
753
|
+
@writer.puts "rm(#{RinRuby_Parse_String})"
|
754
|
+
return true if result == [0]
|
755
|
+
raise ParseError, "Parse error"
|
756
|
+
end
|
757
|
+
|
758
|
+
def find_R_on_windows(cygwin)
|
759
|
+
path = '?'
|
760
|
+
for root in [ 'HKEY_LOCAL_MACHINE', 'HKEY_CURRENT_USER' ]
|
761
|
+
`reg query "#{root}\\Software\\R-core\\R" /v "InstallPath"`.split("\n").each do |line|
|
762
|
+
next if line !~ /^\s+InstallPath\s+REG_SZ\s+(.*)/
|
763
|
+
path = $1
|
764
|
+
while path.chomp!
|
765
|
+
end
|
766
|
+
break
|
767
|
+
end
|
768
|
+
break if path != '?'
|
769
|
+
end
|
770
|
+
raise "Cannot locate R executable" if path == '?'
|
771
|
+
if cygwin
|
772
|
+
path = `cygpath '#{path}'`
|
773
|
+
while path.chomp!
|
774
|
+
end
|
775
|
+
path.gsub!(' ','\ ')
|
776
|
+
else
|
777
|
+
path.gsub!('\\','/')
|
778
|
+
end
|
779
|
+
for hierarchy in [ 'bin', 'bin/i386', 'bin/x64' ]
|
780
|
+
target = "#{path}/#{hierarchy}/Rterm.exe"
|
781
|
+
if File.exists? target
|
782
|
+
return %Q<"#{target}">
|
783
|
+
end
|
784
|
+
end
|
785
|
+
raise "Cannot locate R executable"
|
786
|
+
end
|
787
|
+
|
788
|
+
end
|
789
|
+
|
790
|
+
if ! defined?(R)
|
791
|
+
#R is an instance of RinRuby. If for some reason the user does not want R to be initialized (to save system resources), then create a default value for R (e.g., <b>R=2</b> ) in which case RinRuby will not overwrite the value of R.
|
792
|
+
|
793
|
+
R = RinRuby.new
|
794
|
+
end
|
795
|
+
|