Class: FeldtRuby::RCommunicator

Inherits:
Object
  • Object
show all
Includes:
Statistics::DesignOfExperiments, Statistics::Plotting
Defined in:
lib/feldtruby/statistics.rb,
lib/feldtruby/statistics.rb,
lib/feldtruby/statistics/design_of_experiments.rb

Overview

RCommunicator uses RinRuby to communicate with an instance of R. We extend the basic RinRuby by using json to tunnel back and forth.

Defined Under Namespace

Classes: Rvalue

Constant Summary

Constants included from Statistics::Plotting

Statistics::Plotting::GfxFormatToGfxParams

Instance Method Summary collapse

Methods included from Statistics::DesignOfExperiments

#latin_hypercube_sample_of_parameters, #parameters_to_R_data_frame

Methods included from Statistics::Plotting

#density_tile2d, #filled_contour, #gfx_device, #ggplot2_setup_and_theme, #hash_to_R_params, #hexbin_heatmap, #load_csv_files_as_data, #overlaid_densities, #overlaid_densities_from_csv_files, #plot_2dims, #save_graph, #scatter_plot, #smooth_scatter_plot

Constructor Details

#initializeRCommunicator

Returns a new instance of RCommunicator.



12
13
14
15
16
17
18
19
20
21
# File 'lib/feldtruby/statistics.rb', line 12

def initialize
  # Will stay open until closed or the ruby interpreter exits.
  # echo = false and interactive = false
  @r = RinRuby.new(false, false)

  @installed_libraries = []

  setup_r()

end

Instance Method Details

#call(rmethod, *arguments) ⇒ Object

Call an R method named rmethod with (Ruby) arguments. Returns an Integer, Float or an Rvalue (if the returned R value is complex).



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/feldtruby/statistics.rb', line 86

def call(rmethod, *arguments)
  str, args = "", []
  arguments.each_with_index do |arg, index| 
    args << (argname = arg_name(index))
    str += "#{argname} <- fromJSON(\"#{arg.to_json}\");\n"
  end
  resname = res_name(1)
  str += "#{resname} <- toJSON(#{rmethod.to_s}(#{args.join(', ')}));\n"
  @r.eval str
  pull_json_variable(resname)
end

#eval(str) ⇒ Object



48
49
50
# File 'lib/feldtruby/statistics.rb', line 48

def eval(str)
  @r.eval str
end

#include_library(lib) ⇒ Object

Include a library after ensuring it has been installed



29
30
31
32
33
34
35
36
37
# File 'lib/feldtruby/statistics.rb', line 29

def include_library(lib)

  return if @installed_libraries.include?(lib)

  @installed_libraries << lib

  @r.eval "if(!library(#{lib}, logical.return=TRUE)) {install.packages(\"#{lib}\"); library(#{lib});}"

end

#load_feldtruby_r_script(scriptName, reload = false) ⇒ Object

Load R scripts in the feldtruby/R directory.



40
41
42
43
44
45
46
# File 'lib/feldtruby/statistics.rb', line 40

def load_feldtruby_r_script(scriptName, reload = false)
  @loaded_scripts ||= Array.new # Ensure there is an empty array for loaded script names, if this is first call here.
  return if reload == false && @loaded_scripts.include?(scriptName)
  @loaded_scripts << scriptName
  path = File.join(FeldtRuby::TopDirectory, "R", scriptName)
  @r.eval "source(\"#{path}\")"
end

#pull_json_variable(variableName) ⇒ Object

Get the JSON value from a variable in R and parse it back to a Ruby value.



99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/feldtruby/statistics.rb', line 99

def pull_json_variable(variableName)
  res = @r.pull(variableName)
  begin
    Rvalue.new JSON.parse(res)
  rescue JSON::ParserError
    # First try to convert to Integer, then Float if it fails.
    begin
      Kernel::Integer(res)
    rescue ArgumentError
      Kernel::Float(res)
    end
  end
end

#pull_matrix_variable_to_hash_with_column_names(variableName, columnNames) ⇒ Object

Pull a matrix variable into a hash and name the columns according to values in columnNames.



115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/feldtruby/statistics.rb', line 115

def pull_matrix_variable_to_hash_with_column_names(variableName, columnNames)
  var = arg_name(rand(1e5), variableName)
  RC.eval "#{var} <- toJSON(data.frame(#{variableName}));"
  hash = pull_json_variable(var).to_h

  # Now convert back to the proper parameter names and delete the ones generated by lhs.
  index = 0
  columnNames.each do |p|
    name_of_column = "X#{index += 1}"
    hash[p] = hash[name_of_column]
    hash.delete(name_of_column)
  end
  hash
end

#ruby_object_to_R_string(o) ⇒ Object

Convert a Ruby object of one of the types String, Symbol, Array, Integer or Float to a String that can be used in R code/scripts to represent the object.



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
# File 'lib/feldtruby/statistics.rb', line 133

def ruby_object_to_R_string(o)

    case o

    when String
      return o.inspect

    when Symbol
      return o.to_s

    when Array
      elems = o.map {|e| ruby_object_to_R_string(e)}.join(", ")
      return "c(#{elems})"

    when Integer
      return o.to_s

    when Float
      return o.to_s

    else
      raise "Cannot represent object #{o} in valid R code"

    end

end

#setup_rObject

Include necessary libraries.



24
25
26
# File 'lib/feldtruby/statistics.rb', line 24

def setup_r
  include_library("rjson")
end

#subst_eval(script, scriptNameToRubyValues) ⇒ Object

Given a script that has variable references in the form “name” insert the ruby objects mapped from these names in scriptNameToRubyValues



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/feldtruby/statistics.rb', line 54

def subst_eval(script, scriptNameToRubyValues)

  scriptNameToRubyValues.each do |key, value|

    script = script.gsub("_#{key.to_s}_", ruby_object_to_R_string(value))

  end

  #puts "Eval'ing script:\n#{script}"
  eval script

end