Class: Report_html

Inherits:
Object
  • Object
show all
Defined in:
lib/report_html/report_html.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash_vars, title = "report", data_from_files = false) ⇒ Report_html



9
10
11
12
13
14
15
16
# File 'lib/report_html/report_html.rb', line 9

def initialize(hash_vars, title = "report", data_from_files = false)
  @all_report = ""
  @title = title
  @hash_vars = hash_vars
  @data_from_files = data_from_files
  @plots_data = []
  @count_objects = 0
end

Instance Method Details

#add_header_row_names(data, options) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/report_html/report_html.rb', line 92

def add_header_row_names(data, options)
  if options[:add_header_row_names] # This check if html object needs a default header/row_names or not
    if !options[:header]
      range = 0..(data.first.length - 1)
      data.unshift(range.to_a)
    end
    if !options[:row_names]
      data.each_with_index do |row, i|
        row.unshift(i) 
      end
    end
  end
end

#add_sample_attributes(data_structure, options) ⇒ Object

CANVASXPRESS METHODS




241
242
243
244
245
246
247
248
249
# File 'lib/report_html/report_html.rb', line 241

def add_sample_attributes(data_structure, options)
  parsed_sample_attributes = {}
  options[:sample_attributes].each do |key, col|
    data = get_data({id: options[:id], fields: [col], text: true})
    data.shift if options[:header]
    parsed_sample_attributes[key] = data.flatten 
  end
  data_structure['x'] = parsed_sample_attributes
end

#assign_rgb(link_data) ⇒ Object



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'lib/report_html/report_html.rb', line 522

def assign_rgb(link_data)
  colors = {
    'red' => [255, 0, 0],
    'green' => [0, 255, 0],
    'black' => [0, 0, 0],
    'yellow' => [255, 255, 0],
    'blue' => [0, 0, 255],
    'gray' => [128, 128, 128],
    'orange' => [255, 165, 0],
    'cyan' => [0, 255, 255],
    'magenta' => [255, 0, 255]
  }
  link_data.each do |link|
    code = colors[link[0]]
    if !code.nil?
      link[0] = "rgb(#{code.join(',')})"
    else
      raise "Color link #{link} is not allowed. The allowed color names are: #{colors.keys.join(' ')}"
    end
  end
end

#barplot(user_options = {}, &block) ⇒ Object



373
374
375
376
377
378
379
380
381
# File 'lib/report_html/report_html.rb', line 373

def barplot(user_options = {}, &block)
  default_options = {
    row_names: true
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    config['graphType'] = 'Bar'
  end
  return html_string
end

#boxplot(user_options = {}, &block) ⇒ Object



393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/report_html/report_html.rb', line 393

def boxplot(user_options = {}, &block)
  default_options = {
    row_names: true,
    header: true
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    config['graphType'] = 'Boxplot'
    options[:mod_data_structure] = 'boxplot'
    if options[:extracode].nil?
      options[:extracode] = "C#{object_id}.groupSamples([\"Factor\"]);"
    end
  end
  return html_string
end

#build(template) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/report_html/report_html.rb', line 18

def build(template)
  renderered_template = ERB.new(template).result(binding)
  @all_report = "<HTML>\n"
  make_head
  build_body do 
    renderered_template
  end
  @all_report << "\n</HTML>"
end

#build_bodyObject



28
29
30
# File 'lib/report_html/report_html.rb', line 28

def build_body
  @all_report << "<body onload=\"initPage();\">\n#{yield}\n</body>\n"
end

#canvasXpress_main(user_options, block = nil) {|options, config, samples, vars, values, object_id| ... } ⇒ Object

Yields:

  • (options, config, samples, vars, values, object_id)


267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/report_html/report_html.rb', line 267

def canvasXpress_main(user_options, block = nil)
  # Handle arguments
  #------------------------------------------
  options = {
    id: nil,
    fields: [],
    data_format: 'one_axis',
    responsive: true,
    height: '600px',
    width: '600px',
    header: false,
    row_names: false,
    add_header_row_names: true,
    transpose: true,
    x_label: 'x_axis',
    title: 'Title',
    sample_attributes: {},
    config: {},
    after_render: [],
    treeBy: 's'
  }
  options.merge!(user_options)
  config = {
    'toolbarPermanent' => true,
    'xAxisTitle' => options[:x_label],
    'title' => options[:title]
  }
  if  !options[:tree].nil?
    set_tree(options, config)
  end
  config.merge!(options[:config])
  # Data manipulation
  #------------------------------------------
  no_data_string = ERB.new("<div width=\"#{options[:width]}\" height=\"#{options[:height]}\" > <p>NO DATA<p></div>").result(binding)
  data_array = get_data(options)
  return no_data_string if data_array.empty?
  block.call(data_array) if !block.nil?
  object_id = "obj_#{@count_objects}_"
  raise("ID #{options[:id]} has not data") if data_array.nil?
  row_length = data_array.first.length
  samples = data_array.shift[1..row_length]
  return no_data_string if data_array.empty?
  vars = []
  data_array.each do |row|
    vars << row.shift
  end
  values = data_array

  yield(options, config, samples, vars, values, object_id)
  # Build JSON objects and Javascript code
  #-----------------------------------------------
  @count_objects += 1
  data_structure = {
    'y' => {
      'vars' => vars,
      'smps' => samples,
      'data' => values
    }
  }
  events = false
  info = false
  afterRender = options[:after_render]
  if options[:mod_data_structure] == 'boxplot'
    data_structure['y']['smps'] = nil
    data_structure.merge!({ 'x' => {'Factor' => samples}})
  elsif options[:mod_data_structure] == 'circular'
    data_structure.merge!({ 'z' => {'Ring' => options[:ring_assignation]}})
  end
  add_sample_attributes(data_structure, options) if !options[:sample_attributes].empty?
  extracode = "#{options[:extracode]}\n"
  extracode << "C#{object_id}.groupSamples(#{options[:group_samples]})\n" if !options[:group_samples].nil?
  plot_data = "
  var data = #{data_structure.to_json};
        var conf = #{config.to_json}; 
        var events = #{events.to_json};
        var info = #{info.to_json};
        var afterRender = #{afterRender.to_json};                
        var C#{object_id} = new CanvasXpress(\"#{object_id}\", data, conf, events, info, afterRender);\n#{extracode}"
        @plots_data << plot_data
       
        responsive = ''
        responsive = "responsive='true'" if options[:responsive]
  html = "<canvas  id=\"#{object_id}\" width=\"#{options[:width]}\" height=\"#{options[:height]}\" aspectRatio='1:1' #{responsive}></canvas>"
  return ERB.new(html).result(binding)
end

#circular(user_options = {}, &block) ⇒ Object



486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/report_html/report_html.rb', line 486

def circular(user_options = {}, &block)
  default_options = {
    ring_assignation: [],
    ringsType: [],
    ringsWeight: []
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    options[:mod_data_structure] = 'circular'
    config['graphType'] = 'Circular'
    config['segregateVariablesBy'] = ['Ring']
    if default_options[:ringsType].empty?
      config['ringsType'] = Array.new(vars.length, 'heatmap')
    else
      config['ringsType'] = default_options[:ringsType]
    end
    if default_options[:ringsWeight].empty?
      size = 100/vars.length
      config['ringsWeight'] = Array.new(vars.length, size)
    else
      config['ringsWeight'] = default_options[:ringsWeight]
    end
    if default_options[:ring_assignation].empty?
      options[:ring_assignation] = Array.new(vars.length) {|index| (index + 1).to_s}
    else
      options[:ring_assignation] = default_options[:ring_assignation].map{|item| item.to_s}
    end
    if !default_options[:links].nil?
      if !@hash_vars[default_options[:links]].nil? && !@hash_vars[default_options[:links]].empty?
        link_data = get_data({id: default_options[:links], fields: [], add_header_row_names: false, text: true, transpose: false}) 
        config['connections'] = assign_rgb(link_data)
      end
    end
  end
  return html_string
end

#embed_img(img_file, img_attribs = nil) ⇒ Object

EMBED FILES



547
548
549
550
551
552
553
# File 'lib/report_html/report_html.rb', line 547

def embed_img(img_file, img_attribs = nil)
  img_content = File.open(img_file).read
  img_base64 = Base64.encode64(img_content)
  format = File.basename(img_file).split('.').last
  img_string = "<img #{img_attribs} src=\"data:image/#{format};base64,#{img_base64}\">"
  return img_string
end

#embed_pdf(pdf_file, pdf_attribs = nil) ⇒ Object



555
556
557
558
559
560
# File 'lib/report_html/report_html.rb', line 555

def embed_pdf(pdf_file, pdf_attribs = nil)
  pdf_content = File.open(pdf_file).read
  pdf_base64 = Base64.encode64(pdf_content)
  pdf_string = "<embed #{pdf_attribs} src=\"data:application/pdf;base64,#{pdf_base64}\" type=\"application/pdf\"></embed>"
  return pdf_string
end

#extract_data(options) ⇒ Object



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

def extract_data(options)
  data = []
  ids = options[:id]
  fields = options[:fields]
  ids = ids.split(',') if ids.class == String && ids.include?(',') # String syntax
  if ids.class == Array
    fields = fields.split(';').map{|data_fields| data_fields.split(',').map{|fields| fields.to_i} } if fields.class == String # String syntax
    ids.each_with_index do |id, n|
      data_file = extract_fields(id, fields[n])
      if data.empty?
        data.concat(data_file)
      else
        data.each_with_index do |row, n|
          data[n] = row + data_file[n]
        end
      end
    end
  else
    fields = fields.first if fields.class == Array
    data = extract_fields(ids, options[:fields])
  end
  return data
end

#extract_fields(id, fields) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
# File 'lib/report_html/report_html.rb', line 130

def extract_fields(id, fields)
  data = []
  @hash_vars[id].each do |row|
    if fields.empty?
      data << row.dup # Dup generates a array copy that avoids to modify original objects on data manipulation creating graphs
    else
      data << fields.map{|field| row[field]} #Map without bang do the same than dup
    end
  end
  return data
end

#get_cell_align(align_vector, position) ⇒ Object



219
220
221
222
223
224
225
226
# File 'lib/report_html/report_html.rb', line 219

def get_cell_align(align_vector, position)
  cell_align = '' 
  if !align_vector.empty? 
    align = align_vector[position]
    cell_align = "align=\"#{align}\""
  end
  return cell_align
end

#get_col_n_row_span(table) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/report_html/report_html.rb', line 194

def get_col_n_row_span(table)
  colspan = []
  rowspan = []
  last_row = 0
  table.each_with_index do |row, r|
    rowspan << Array.new(row.length, 1)
    colspan << Array.new(row.length, 1)
    last_col = 0
    row.each_with_index do |col, c|
      if col == 'colspan'
        colspan[r][last_col] += 1
      else
        last_col = c
      end
      if col == 'rowspan'
        rowspan[last_row][c] += 1
      else
        last_row = r
      end
    end
  end
  return rowspan, colspan
end

#get_data(options) ⇒ Object

DATA MANIPULATION METHODS




68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/report_html/report_html.rb', line 68

def get_data(options)
  data = []
  data = extract_data(options)
  if !data.empty?
    if @data_from_files # If data on container is loaded using html_report as lib, we don't care about data format
              # if data comes from files and is loaded as strings. We need to format correctly the data.
      rows = data.length
      cols = data.first.length
      if !options[:text]
        rows.times do |r|
          cols.times do |c|
            next if r == 0 && options[:header]
            next if c == 0 && options[:row_names]
            data[r][c] = data[r][c].to_f
          end
        end
      end
    end
    add_header_row_names(data, options)
    data = data.transpose if options[:transpose]
  end
  return data
end

#get_reportObject

return all html string



51
52
53
54
# File 'lib/report_html/report_html.rb', line 51

def get_report #return all html string
  renderer = ERB.new(@all_report)
  return renderer.result(binding) #binding does accesible all the current ruby enviroment to erb
end

#get_span(colspan, rowspan, row, col) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/report_html/report_html.rb', line 181

def get_span(colspan, rowspan, row, col)
  span = []
  colspan_value = colspan[row][col]
  rowspan_value = rowspan[row][col]
  if colspan_value > 1
    span << "colspan=\"#{colspan_value}\""
  end
  if rowspan_value > 1
    span << "rowspan=\"#{rowspan_value}\""
  end
  return span.join(' ')
end

#heatmap(user_options = {}, &block) ⇒ Object



383
384
385
386
387
388
389
390
391
# File 'lib/report_html/report_html.rb', line 383

def heatmap(user_options = {}, &block)
  default_options = {
    row_names: true
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    config['graphType'] = 'Heatmap' 
  end
  return html_string
end

#line(user_options = {}, &block) ⇒ Object



353
354
355
356
357
358
359
360
361
# File 'lib/report_html/report_html.rb', line 353

def line(user_options = {}, &block)
  default_options = {
    row_names: true     
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    config['graphType'] = 'Line'  
  end
  return html_string
end

#make_headObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/report_html/report_html.rb', line 32

def make_head
  @all_report << "\t<title>#{@title}</title>
    <head>
        <meta http-equiv=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\">
        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
        <meta http-equiv=\"Content-Language\" content=\"en-us\" />

        <link rel=\"stylesheet\" href=\"js/canvasXpress.css\" type=\"text/css\"/>
        <script type=\"text/javascript\" src=\"js/canvasXpress.min.js\"></script>
        <script>
        var initPage = function () {        
          <% @plots_data.each do |plot_data| %>
            <%= plot_data %>
          <% end %>
        }
      </script>
    </head>\n"
end

#pie(user_options = {}, &block) ⇒ Object



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/report_html/report_html.rb', line 408

def pie(user_options = {}, &block) 
  default_options = {
    transpose: false
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    config['graphType'] = 'Pie'
    if samples.length > 1
      config['showPieGrid'] = true
      config['xAxis'] = samples 
      config['layout'] = "#{(samples.length.to_f/2).ceil}X2" if config['layout'].nil?
      config['showPieSampleLabel'] = true if config['showPieSampleLabel'].nil?
    end
  end
  return html_string
end

#prepare_table_attribs(attribs) ⇒ Object



228
229
230
231
232
233
234
235
236
# File 'lib/report_html/report_html.rb', line 228

def prepare_table_attribs(attribs)
  attribs_string = ''
  if !attribs.empty?
    attribs.each do |attrib, value|
      attribs_string << "#{attrib}= \"#{value}\" "
    end
  end
  return attribs_string
end

#scatterbubble2D(user_options = {}, &block) ⇒ Object



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/report_html/report_html.rb', line 445

def scatterbubble2D(user_options = {}, &block)
  default_options = {
    row_names: true,
    transpose: false
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    config['graphType'] = 'ScatterBubble2D'
    if options[:xAxis].nil? 
      config['xAxis'] = [samples[0]]
    else
      config['xAxis'] = options[:xAxis]
    end
    if options[:yAxis].nil? 
      config['yAxis'] = [samples[1]]
    else
      config['yAxis'] = options[:yAxis]
    end
    if options[:zAxis].nil? 
      config['zAxis'] = [samples[2]]
    else
      config['zAxis'] = options[:zAxis]
    end
    if default_options[:y_label].nil?
      config['yAxisTitle'] = 'y_axis'
    else
      config['yAxisTitle'] = default_options[:y_label]
    end
    if default_options[:z_label].nil?
      config['zAxisTitle'] = 'z_axis'
    else
      config['zAxisTitle'] = default_options[:z_label]
    end
    if !options[:upper_limit].nil? && !options[:lower_limit].nil? && !options[:ranges].nil?
      diff = (options[:upper_limit] - options[:lower_limit]).to_f/options[:ranges]
      sizes = Array.new(options[:ranges]) {|index| options[:lower_limit] + index * diff}
      config['sizes'] = sizes
    end
  end
  return html_string
end

#sccater2D(user_options = {}, &block) ⇒ Object



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/report_html/report_html.rb', line 424

def sccater2D(user_options = {}, &block)
  default_options = {
    row_names: false,
    transpose: false
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    config['graphType'] = 'Scatter2D'
    config['xAxis'] = [samples.first] if config['xAxis'].nil? 
    config['yAxis'] = samples[1..samples.length-1] if config['yAxis'].nil?
    if default_options[:y_label].nil?
      config['yAxisTitle'] = 'y_axis'
    else
      config['yAxisTitle'] = default_options[:y_label]
    end
    if options[:regressionLine]
      options[:extracode] = "C#{object_id}.addRegressionLine();"
    end
  end
  return html_string
end

#set_tree(options, config) ⇒ Object



256
257
258
259
260
261
262
263
264
265
# File 'lib/report_html/report_html.rb', line 256

def set_tree(options, config)
  tree = tree_from_file(options[:tree])
  if options[:treeBy] == 's'
    config['smpDendrogramNewick'] = tree
    config['samplesClustered'] = true
  elsif options[:treeBy] == 'v'
    config['varDendrogramNewick'] = tree
    config['variablesClustered'] = true
  end
end

#stacked(user_options = {}, &block) ⇒ Object



363
364
365
366
367
368
369
370
371
# File 'lib/report_html/report_html.rb', line 363

def stacked(user_options = {}, &block)
  default_options = {
    row_names: true,
  }.merge!(user_options)
  html_string = canvasXpress_main(default_options, block) do |options, config, samples, vars, values, object_id|
    config['graphType'] = 'Stacked' 
  end
  return html_string
end

#table(user_options = {}, &block) ⇒ Object

TABLE METHODS




144
145
146
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
# File 'lib/report_html/report_html.rb', line 144

def table(user_options = {}, &block)
  options = {
    id: nil,
    header: false,
    row_names: false,
    add_header_row_names: false,
    transpose: false,
    fields: [],
    border: 1,
    cell_align: [],
    attrib: {}
  }
  options.merge!(user_options)
  table_attr = prepare_table_attribs(options[:attrib])
  array_data = get_data(options)
  block.call(array_data) if !block.nil?
  rowspan, colspan = get_col_n_row_span(array_data)
  html = "
  <table border=\"#{options[:border]}\" #{table_attr}>
    <% array_data.each_with_index do |row, i| %>
      <tr>
        <% row.each_with_index do |cell, j|
          if cell != 'colspan' && cell != 'rowspan' 
            if i == 0 && options[:header] %>
              <th <%= get_span(colspan, rowspan, i, j) %>><%= cell %></th>
            <% else %>
              <td <%= get_cell_align(options[:cell_align], j) %> <%= get_span(colspan, rowspan, i, j) %>><%= cell %></td>
            <% end 
          end %>
        <% end %>
      </tr>
    <% end %>
  </table>
  "
  return ERB.new(html).result(binding)
end

#tree_from_file(file) ⇒ Object



251
252
253
254
# File 'lib/report_html/report_html.rb', line 251

def tree_from_file(file)
        string_tree = File.open(file).read.gsub("\n", '')
        return string_tree
end

#write(file) ⇒ Object



56
57
58
59
60
61
# File 'lib/report_html/report_html.rb', line 56

def write(file)
  dir = File.dirname(file)
  string_report = get_report
  FileUtils.cp_r(JS_FOLDER, dir) 
  File.open(file, 'w'){|f| f.puts string_report}
end