Module: Wrnap::Graphing::R

Defined in:
lib/wrnap/graphing/r.rb

Class Method Summary collapse

Class Method Details

.graph(width: 8, height: 6, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/wrnap/graphing/r.rb', line 5

def graph(width: 8, height: 6, &block)
  if const_defined?(:RinRuby)
    begin
      generate_graph(r_instance = RinRuby.new(false), width, height, &block).tap { r_instance.close }
    rescue RuntimeError => e
      raise unless e.message == "Unsupported data type on R's end"
    end
  else
    raise RuntimeError.new("Your system does not appear to have R installed, and thus the RinRuby gem was not loaded.")
  end
end

.histogram(data, title: nil, x_label: "Bins", num_bins: false, bin_size: 1, x_arrow: false, relative: false, filename: false) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/wrnap/graphing/r.rb', line 121

def histogram(data, title: nil, x_label: "Bins", num_bins: false, bin_size: 1, x_arrow: false, relative: false, filename: false)
  half     = bin_size / 2.0
  range    = Range.new((data.min - half).floor, (data.max + half).ceil)
  breaks   = num_bins ? num_bins : (range.min + half).step(range.max + half, bin_size).to_a

  graph do |r|
    r.assign("histogram.data", data)
    r.assign("histogram.breaks", breaks)

    r.eval <<-STR
      hist(
        histogram.data,
        breaks   = histogram.breaks,
        xlab     = #{expressionify(x_label)},
        main     = #{expressionify(title || "Histogram")},
        freq     = #{relative ? 'F' : 'T'},
        cex.main = 0.9,
        cex.lab  = 0.9,
        cex.axis = 0.9
      )
    STR

    r.eval("abline(v = #{x_arrow}, lty = 'dashed')") if x_arrow
  end
end

.line_graph(data, title: nil, type: ?l, x_label: "Independent", y_label: "Dependent", filename: false) ⇒ Object



74
75
76
# File 'lib/wrnap/graphing/r.rb', line 74

def line_graph(data, title: nil, type: ?l, x_label: "Independent", y_label: "Dependent", filename: false)
  overlay([{ data: data }], title: title, type: type, x_label: x_label, y_label: y_label, legend: false, filename: filename)
end

.matrix_heatmap(x, y, z, title: nil, x_label: "Column index", y_label: "Row index", filename: false, num_colors: 64) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/wrnap/graphing/r.rb', line 147

def matrix_heatmap(x, y, z, title: nil, x_label: "Column index", y_label: "Row index", filename: false, num_colors: 64)
  graph do |r|
    if r.pull("ifelse('Matrix' %in% rownames(installed.packages()), 1, -1)") > 0
      if forced_square = (x.max != y.max)
        x << [x, y].map(&:max).max
        y << [x, y].map(&:max).max
        z << 0
      end

      r.assign("matrix.i", x)
      r.assign("matrix.j", y)
      r.assign("matrix.x", z)
      r.eval <<-STR
        require("Matrix")
        matrix.data <- sparseMatrix(
        i      = matrix.i,
        j      = matrix.j,
        x      = matrix.x,
        index1 = F
        )
        
        filtered.values <- Filter(function(i) { is.finite(i) & i != 0 }, matrix.x)
        print(apply(as.matrix(matrix.data), 2, rev))
        print(c(sort(filtered.values)[2], max(filtered.values)))

        image(
          x    = 1:max(c(dim(matrix.data)[[1]], dim(matrix.data)[[2]])),
          y    = 1:max(c(dim(matrix.data)[[1]], dim(matrix.data)[[2]])),
          z    = as.matrix(matrix.data),
          col  = rev(heat.colors(#{num_colors})),
          zlim = #{forced_square ? "c(sort(filtered.values)[2], max(filtered.values))" : "c(min(filtered.values), max(filtered.values))"},
          xlab = "#{x_label} (1-indexed)",
          ylab = "#{y_label} (1-indexed)"
        )
        title(#{expressionify(title || "Matrix Heatmap")})
      STR
    else
      puts "Please install the Matrix package for R before using this function."
    end
  end
end

.overlay(data, title: nil, type: ?l, x_label: "Independent", y_label: "Dependent", legend: "topleft", filename: false) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/wrnap/graphing/r.rb', line 17

def overlay(data, title: nil, type: ?l, x_label: "Independent", y_label: "Dependent", legend: "topleft", filename: false)
  # data: [{ data: [[x_0, y_0], ..., [x_n, y_n]], legend: "Line 1" }, ...]

  x_points = data.map { |hash| hash[:data].map(&:first) }
  y_points = data.map { |hash| hash[:data].map(&:last) }
  x_range  = Range.new(x_points.map(&:min).min.floor, x_points.map(&:max).max.ceil)
  y_range  = Range.new(y_points.map(&:min).min.floor, y_points.map(&:max).max.ceil)

  graph do |r|
    r.assign("legend.titles", data.each_with_index.map { |hash, index| hash[:legend] || "Line #{index + 1}" })
    r.eval("line.colors <- rainbow(%d)" % data.size)
    r.eval("plot(0, 0, type = 'n', cex = .75, cex.axis = .9, xlab = '', ylab = '', xlim = c(%d, %d), ylim = c(%d, %d))" % [
      x_range.min, x_range.max, y_range.min, y_range.max
    ])

    data.each_with_index do |hash, index|
      r.assign("line_graph.x.%d" % index, x_points[index])
      r.assign("line_graph.y.%d" % index, y_points[index])

      r.eval <<-STR
        lines(
          line_graph.x.#{index},
          line_graph.y.#{index},
          col  = line.colors[#{index + 1}],
          type = "#{type}",
          pch  = #{index}
        )
      STR
    end

    r.eval <<-STR
      title(
        xlab     = #{expressionify(x_label)},
        ylab     = #{expressionify(y_label)},
        main     = #{expressionify(title || "Line Graph")},
        cex.main = .9,
        cex.lab  = .9
      )
    STR

    if legend
      r.eval <<-STR
        legend(
          "#{legend}",
          legend.titles,
          bty = "o",
          bg  = rgb(1, 1, 1, .5, 1),
          col = line.colors,
          lty = rep(1, #{data.size}),
          pch = 0:#{data.size},
          cex = .6
        )
      STR
    end
  end
end

.roc(data, title: nil, baseline: true, filename: false) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/wrnap/graphing/r.rb', line 82

def roc(data, title: nil, baseline: true, filename: false)
  # data: [[-0.894, 1.0], [-0.950, 1.0], [0.516, -1.0], ..., [0.815, -1.0], [0.740, -1.0]]
  auc            = ROC.auc(data)
  title_with_auc = title ? "%s (AUC: %.4f)" % [title, auc] : "AUC: %.4f" % auc
  overlay(
    [{ data: ROC.curve_points(data) }, { data: [[0, 0], [1, 1]] }],
    title:    title_with_auc,
    x_label:  "False positive rate",
    y_label:  "True positive rate",
    legend:   false,
    filename: filename
  )
end

.roc_overlay(data, title: nil, auc_in_legend: true, filename: false) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/wrnap/graphing/r.rb', line 96

def roc_overlay(data, title: nil, auc_in_legend: true, filename: false)
  # [{ data: [[-0.894, 1.0], [-0.950, 1.0], [0.516, -1.0], ..., [0.815, -1.0], [0.740, -1.0]], legend: "ROC 1" }, ...]
  formatted_data = data.map do |hash|
    curve_points = ROC.curve_points(hash[:data])

    if auc_in_legend
      auc    = ROC.auc(hash[:data])
      legend = hash[:legend] ? "%s (AUC: %.4f)" % [hash[:legend], auc] : "AUC: %.4f" % auc

      hash.merge({ data: curve_points, legend: legend })
    else
      hash.merge({ data: curve_points })
    end
  end

  overlay(
    formatted_data,
    title:    title,
    x_label:  "False positive rate",
    y_label:  "True positive rate",
    legend:   "bottomright",
    filename: filename
  )
end

.scatterplot(data, title: nil, x_label: "Independent", y_label: "Dependent", filename: false) ⇒ Object



78
79
80
# File 'lib/wrnap/graphing/r.rb', line 78

def scatterplot(data, title: nil, x_label: "Independent", y_label: "Dependent", filename: false)
  line_graph(data, title: title || "Scatterplot", type: ?p, x_label: x_label, y_label: y_label, filename: filename)
end