Class: GraphKit

Inherits:
KitHash show all
Includes:
Kit, Log
Defined in:
lib/graphkit.rb,
lib/graphkit/mm.rb,
lib/graphkit/csv.rb,
lib/graphkit/gnuplot.rb,
lib/graphkit/vtk_legacy_ruby.rb

Defined Under Namespace

Classes: AxisKit, DataError, DataKit, GnuplotPlotOptions, GnuplotSetOptions, GnuplotVariables, MultiWindow

Constant Summary collapse

AXES =
[:x, :y, :z, :f]
DEFAULT_COLOURS =
{0 => "#df0000", 1 => "#00df00", 2 => "#0000df", 3 => "#a000a0", 4 => "#0090a0", 5 => "#e59500", 7 => "#82c290", 8 => "#f76dba", 9 => "#c20f00", 10 => "#4f1099"}
DEFAULT_COLOURS_GNUPLOT =
DEFAULT_COLOURS
DEFAULT_COLOURS_MATHEMATICA =
DEFAULT_COLOURS.inject({}) do |hash, (i, coll)|
  hash[i] = coll.sub(/#/, '').scan(/.{2}/).map{|str| (eval("0x#{str}").to_f / 255.0).round(2)}
  hash  
end
GNUPLOT_DEFAULT_TERM =
ENV['GRAPHKIT_TERM'] || "x11"
GNUPLOT_DEFAULT_COLOURS =
{0 => "#df0000", 1 => "#00df00", 2 => "#0000df", 3 => "#a000a0", 4 => "#0090a0", 5 => "#e59500", 6 => "#82c290", 7 => "#f76dba", 8 => "#c20f00", 9 => "#4f1099"}
@@old_gnuplot_sets =

AXES.each do |axisname| [:name, :label, :units, :range].each do |option| define_method(axisname + option)[axisname] define_method(axisname + option + ‘=’.to_sym){|value| self[axisname] = value} end end

[ :dgrid3d, :title, :style, :term, :terminal, :pointsize, :log_axis, :key, :pm3d, :palette, :view, :cbrange, :contour, :nosurface, :cntrparam, :preamble, :xtics, :ytics]

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Kit

#check, #method_missing

Methods inherited from KitHash

from_hash, #inspect

Methods inherited from Hash

#modify

Constructor Details

#initialize(naxes = 0, hash = {}) ⇒ GraphKit

Greate a new graphkit. Rarely used: see GraphKit.autocreate and GraphKit.quick_create



302
303
304
305
306
307
308
309
# File 'lib/graphkit.rb', line 302

def initialize(naxes=0, hash = {})
  logf :initialize
  super()
  self[:naxes] = naxes 
  self[:data] = []
  hash
#     @gnuplot_options = GnuplotOptions.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Kit

Class Method Details

.autocreate(*hashes) ⇒ Object

Create a new graphkit with one hash for every datakit (each datakit corresponds to a line or surface on the graph). Each hash should contain specifications for the axes of the graph (see AxisKit#autocreate).

E.g. kit = GraphKit.autocreate( { x: [1,2,3], title ‘x’, units: ‘m’, y: [1,4,9], title ‘x^2’, units: ‘m^2’ } )

will create a two dimensional graph that plots x^2 against x.



333
334
335
336
# File 'lib/graphkit.rb', line 333

def self.autocreate(*hashes)
  Log.logf :autocreate
  new(hashes[0].size).autocreate(*hashes)
end

.latex_multiplot(name, options = {}) ⇒ Object



526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'lib/graphkit/gnuplot.rb', line 526

def self.latex_multiplot(name, options={})
  name = name.sub(/\.eps$/, '')
  figure_preamble = options[:preamble] || "\\\\documentclass[graphicx,reprint,twocolumn]{revtex4}\n%\\documentclass[aip,reprint]{revtex4-1}\n\\\\usepackage{graphics,bm,overpic,color}\n\\\\usepackage[tight]{subfigure}\n\n\\\\pagestyle{empty}\n\\\\begin{document}\n\\\\begin{figure}\n"

  figure_postamble = options[:postamble] || "\\\\end{figure}\n\\\\end{document}\n"
  text = "\#{figure_preamble}\n\#{yield}\n\#{figure_postamble}\n"
    File.open("#{name}.tex", 'w'){|f| f.puts text}
  raise 'latex failed'  unless system "latex #{name}.tex"
  raise 'dvips failed' unless system "dvips #{name}.dvi"
  FileUtils.rm "#{name}.eps" if FileTest.exist? "#{name}.eps"
  raise 'ps2eps failed' unless system "ps2eps #{name}.ps"
end

.quick_create(*datasets) ⇒ Object

Create a new graphkit without providing any labels.

E.g. kit = GraphKit.quick_create( [ [1,2,3], [1,4,9] ] )

will create a two dimensional graph that plots x^2 against x.



359
360
361
362
363
364
365
366
367
368
# File 'lib/graphkit.rb', line 359

def self.quick_create(*datasets)
  hashes = datasets.map do |data|
    hash = {}
    data.each_with_index do |dat, i|
      hash[AXES[i]] = {data: dat}
    end
    hash
  end
  autocreate(*hashes)
end

Instance Method Details

#+(other) ⇒ Object

Combine with another graph; titles and labels from the first graph will override the second.



431
432
433
434
435
436
437
438
# File 'lib/graphkit.rb', line 431

def +(other)
  check(['other.naxes', other.naxes, self.naxes])
  new = self.class.new(naxes)
  new.modify(other, [:data])
  new.modify(self, [:data])
  new.data = self.data + other.data
  new
end

#apply_gnuplot_options(options) ⇒ Object

Modify the graphkit according to the options hash



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/graphkit/gnuplot.rb', line 247

def apply_gnuplot_options(options)
  options = options.dup # No reason to modify the original hash
  logf :gnuplot
  processes = %x[ps | grep 'gnuplot'].scan(/^\s*\d+/).map{|match| match.to_i}
  if options[:outlier_tolerance]
    raise "Can only get rid of outliers for 1D or 2D data" if naxes > 2
    data.each do |datakit|
      datakit.outlier_tolerance = options[:outlier_tolerance]
#         datakit.calculate_outliers
      datakit.exclude_outliers
    end
    options.delete(:outlier_tolerance)
  end
  self.live = options[:live]
  options.delete(:live) if live
  if (self.view =~ /map/ or self.pm3d =~ /map/) and naxes < 4
    self.cbrange ||= self.zrange
    options[:cbrange] ||= options[:zrange] if options[:zrange]
  end
  if options[:eval]
    eval(options[:eval])
    options.delete(:eval)
  end
  options.each   do |k,v|
#             ep option, val if option == :xrange

        #           ep k, v
        set(k, v)
  end
end

#autocreate(*hashes) ⇒ Object

:nodoc: (see GraphKit.autocreate)



372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/graphkit.rb', line 372

def autocreate(*hashes) # :nodoc:  (see GraphKit.autocreate)
  logf :autocreate
  hashes.each{|hash| data.push DataKit.autocreate(hash)}
#     pp data
  [:title, :label, :units, :range].each do |option| 
    data[0].axes.each do |key, axiskit|
#       next unless AXES.include? key
      self[key + option] = axiskit[option].dup if axiskit[option]
    end
  end
  self.title = data[0].title
  check_integrity
  self
end

#check_integrityObject

Check that the graphkit conforms to specification; that the data has dimensions that make sense and that the titles and ranges have the right types.



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/graphkit.rb', line 389

def check_integrity
  logf :check_integrity
  check(['data.class', Array], ['title.class', [String, NilClass]], ['has_legend.class', [Hash, NilClass]])
  [[:units, [String, NilClass]], [:range, [Array, NilClass]], [:label, [String, NilClass]], [:title, [String, NilClass]]].each do |prop, klass|
#       next unless self[prop]
    AXES.each do |key|
#         p prop, klass
#         p instance_eval(prop.to_s + "[#{key.inspect}]"), 'ebb'
      check(["#{key + prop}.class", klass])
#         check(["a key from #{prop}", key, AXES + [:f]])
    end 
  end
  data.each do |datakit|
    check(['class of a member of the data array', datakit.class, DataKit])
    check(['datakit.axes.size', datakit.axes.size, naxes])
    datakit.check_integrity
  end
  return true
end

#closeObject



344
345
346
347
348
349
350
351
352
353
354
# File 'lib/graphkit/gnuplot.rb', line 344

def close
  logf :close
  begin
    #require 'sys/proctable'
    #p Sys::ProcTable.ps.select{ |pe| pe.ppid == pid }
    Process.kill('TERM', pid) if pid
  rescue => err
    puts err, pid
  end
  self.pid = nil
end

#convert(&block) ⇒ Object



483
484
485
486
487
488
489
490
491
492
# File 'lib/graphkit.rb', line 483

def convert(&block)
  #ep 'Converting graph...'
  kit = self.dup
  #p kit

  kit.data.map! do |dk|
    dk.convert(&block)
  end
  kit
end

#convert_rank!(from_to, options = {}) ⇒ Object

convert_rank!([, [1,1,2]])



501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/graphkit.rb', line 501

def convert_rank!(from_to, options={})
  ep "Converting Rank"
  case from_to
  when [[1,1,1], [1,1,2]]
    dependent_dimension = options[:dd] || options[:dependent_dimension] || 2
    other_dims = [0,1,2] - [dependent_dimension]
    od0 = other_dims[0]
    od1 = other_dims[1]
    data.each do |dk|
      new_data = SparseTensor.new(2)
      od0_data = dk.axes[AXES[od0]].data.to_a.uniq.sort
      od1_data = dk.axes[AXES[od1]].data.to_a.uniq.sort

      for i in 0...dk.axes[:x].data.size
        od0_index = od0_data.index(dk.axes[AXES[od0]].data[i])
        od1_index = od1_data.index(dk.axes[AXES[od1]].data[i])
        new_data[[od0_index, od1_index]] = dk.axes[AXES[dependent_dimension]].data[i]
      end
      dk.axes[AXES[od0]].data = od0_data
      dk.axes[AXES[od1]].data = od1_data
      dk.axes[AXES[dependent_dimension]].data = new_data
    end

  else
    raise "Converting from #{from_to[0].inspect} to #{from_to[1].inspect} is not implemented yet."
  end
  eputs self.pretty_inspect
end

#dupObject

Duplicate the graphkit.



423
424
425
426
427
# File 'lib/graphkit.rb', line 423

def dup
  #logf :dup
  #self.class.new(naxes, self)
  eval(inspect)
end

#each_axiskit(*axes, &block) ⇒ Object



453
454
455
456
457
458
459
460
# File 'lib/graphkit.rb', line 453

def each_axiskit(*axes, &block)
  axes = AXES unless axes.size > 0
  axes.each do |axis|
    data.each do |datakit|
      yield(datakit.axes[axis])
    end
  end
end

#extend_using(other, mapping = nil) ⇒ Object



440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/graphkit.rb', line 440

def extend_using(other, mapping = nil)
  if mapping
    mapping.each do |mine, others|
      data[mine].extend_using(other.data[others])
    end
  else
    raise TypeError.new("A graph can only be extended by a graph with the same number of datasets unless a mapping is provided: this graph has #{data.size} and the other graph has #{other.data.size}") unless data.size == other.data.size
    data.each_with_index do |dataset, index|
      dataset.extend_using(other.data[index])
    end
  end
end

#gnuplot(options = {}) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/graphkit/gnuplot.rb', line 299

def gnuplot(options={}) 
  apply_gnuplot_options(options)
  apply_graphkit_standard_options_to_gnuplot
  check_integrity
  if options[:io]
    send_gnuplot_commands(io)
  else
    Gnuplot.open(true) do |io|
        send_gnuplot_commands(io)
        (STDIN.gets) if live
    end
  end
end

#gnuplot_setsObject Also known as: gp



233
234
235
236
237
# File 'lib/graphkit/gnuplot.rb', line 233

def gnuplot_sets
  # gnuplot_options included for back. comp
  self[:gnuplot_sets] ||= @gnuplot_options || GnuplotSetOptions.new
  self[:gnuplot_sets]
end

#gnuplot_variablesObject Also known as: gv



240
241
242
# File 'lib/graphkit/gnuplot.rb', line 240

def gnuplot_variables
  @gnuplot_variables ||= GnuplotVariables.new
end

#gnuplot_write(file_name, options = {}) ⇒ Object



479
480
481
482
483
484
485
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
521
522
523
524
# File 'lib/graphkit/gnuplot.rb', line 479

def gnuplot_write(file_name, options={})
  logf :gnuplot_write
  old_gp_term = gp.term
  old_gp_output = gp.output
  if file_name
    gp.output = file_name
    unless gp.term or options[:terminal]
      case File.extname(file_name)
      when '.pdf'
        gp.term = 'pdf size 20cm,15cm'
      when '.ps'
        gp.term = 'post color'
      when '.eps'
        unless options[:latex]
          gp.term = %[post eps color enhanced size  #{options[:size] or "3.5in,2.33in"}]
        else
          gp.term ||= "epslatex color dashed size #{options[:size] or "3.5in,#{options[:height] or "2.0in"}"} colortext standalone 8"
          (gp.term += " header '#{options[:preamble].inspect.gsub(/\\\n/, "\\\\\\n")}'"; options.delete(:preamble)) if options[:preamble]
        end
      when '.jpg'
        gp.term = "jpeg size  #{options[:size] or "3.5in,2.33in"}"
      when '.png'
        gp.term = "png size  #{options[:size] or "640,480"}"
      when '.gif'
        gp.term = "gif size  #{options[:size] or "640,480"}"
      
      end
    end
  end
  
  gp.output = file_name.sub(/\.eps/, '.tex') if options[:latex]
  options.delete(:size)
  gnuplot(options)
  if options[:latex]
      name = file_name.sub(/\.eps$/, '')
      raise "No file output by gnuplot" unless FileTest.exist? name + '.tex'
      raise 'latex failed' unless system "latex #{name}.tex --interaction nonstopmode --halt-on-error -q"
      raise 'dvips failed' unless system "dvips #{name}.dvi"
      FileUtils.rm "#{name}.eps" if FileTest.exist? "#{name}.eps"
      raise 'ps2eps failed' unless system "ps2eps #{name}.ps"
  end
#     ep file_name
   gp.term = old_gp_term
  gp.output = old_gp_output
  return File.basename(file_name, File.extname(file_name))
end

#lx(*args) ⇒ Object

:nodoc:



339
340
341
# File 'lib/graphkit.rb', line 339

def lx(*args) # :nodoc:
  log_axis(*args)
end

#lx=(val) ⇒ Object

:nodoc: (deprecated)



343
344
345
# File 'lib/graphkit.rb', line 343

def lx=(val) # :nodoc:  (deprecated)
  self.log_axis = val
end

#plot_area_sizeObject



462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/graphkit.rb', line 462

def plot_area_size
  logf :plot_area_size
  shapes = data.map{|datakit| datakit.plot_area_size}.inject do |old,new|
    for i in 0...old.size
      old[i][0] = [old[i][0], new[i][0]].min
      old[i][1] = [old[i][1], new[i][1]].max
    end
    old
  end
  shapes

end

#send_gnuplot_commands(io) ⇒ Object



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
# File 'lib/graphkit/gnuplot.rb', line 313

def send_gnuplot_commands(io)
    self.pid = io.pid
    gnuplot_sets.apply(io)
    gnuplot_variables.apply(io)
    case naxes
    when 1,2
      io << "plot "
    when 3,4
      io << "splot "
    end
    imax = data.size - 1
    data.each_with_index do |dk,i|
      next if i>0 and compress_datakits
      dk.gnuplot_plot_options.with ||= dk.with #b.c.
      dk.gnuplot_plot_options.title ||= dk.title #b.c.
      dk.gnuplot_plot_options.apply(io)
      #p 'imax', imax, i, i == imax
      next if compress_datakits
      io << ", " unless i == imax
    end
    io << "\n"
    data.each_with_index do |dk,i|
      dk.gnuplot(io)
       unless compress_datakits and i<imax
        io << "e\n\n"
       else
         io << "\n\n"
       end
    end
end

#to_csv(options = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/graphkit/csv.rb', line 13

def to_csv(options={})  
  check_integrity
  ep 'to_csv'
  stringio = options[:io] || StringIO.new
  data.each do |dk|
    dk.to_csv(io: stringio)
    stringio <<  "\n\n"
  end
  return stringio.string unless options[:io]
end

#to_mathematicaObject

Convert graphkit into a string which can be used by Mathematica



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/graphkit/mm.rb', line 3

def to_mathematica
  str = ""
  case data[0].ranks
  when [1], [1, 1]
    str = "ListPlot[{#{data.map{|dk| dk.to_mathematica}.join(',')}}"


  end
  pas = plot_area_size
  if (xrange or yrange or zrange)
    str << ", PlotRange -> "
    str << "{#{((0...naxes).to_a.map do |nax| 
      ax = AXES[nax]
      specified_range = (send(ax + :range) or [nil, nil])
      "{#{specified_range.zip(pas[nax]).map{|spec, pasr| (spec or pasr).to_s}.join(',')}}"
    end).join(',')}}"
  end
  str << ", PlotStyle -> {#{(data.size.times.map do |i|
    ((data[i].mtm.plot_style) or "{}")
  end).join(',')}}"

  str << "]"

end

#to_vtk_legacy(options = {}) ⇒ 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
# File 'lib/graphkit/vtk_legacy_ruby.rb', line 17

def to_vtk_legacy(options={}) 
  check_integrity
  ep 'to_vtk_legacy'
  stringio = options[:io] || StringIO.new
   npoints = data.map{|dk| dk.vtk_legacy_size}.sum
  stringio << "# vtk DataFile Version 3.0\nvtk output\nASCII\nDATASET UNSTRUCTURED_GRID\nPOINTS \#{npoints} float\n"
  data.each do |dk|
    dk.vtk_legacy_points(io: stringio)
    #stringio <<  "\n\n"
  end
  #ncells = data.map{|dk| dk.vtk_legacy_cells(action: :count)}.sum
  #ncell_elements = data.map{|dk| dk.vtk_legacy_cells(action: :count_elements)}.sum
  cellstring = ""
  pc = 0
  data.each do |dk|
    cellstring += dk.vtk_legacy_cells pointcount: pc
    pc += dk.vtk_legacy_size
    #stringio <<  "\n\n"
  end
  ncells = cellstring.count("\n")
  ncell_elements = cellstring.scan(/\s+/).size
  stringio << "\nCELLS \#{ncells} \#{ncell_elements}\n"
  stringio << cellstring
  stringio << "\nCELL_TYPES \#{ncells}\n"
  data.each do |dk|
    dk.vtk_legacy_cell_types(io: stringio)
    #stringio <<  "\n\n"
  end
  stringio << "\nPOINT_DATA \#{npoints} \nSCALARS myvals float\nLOOKUP_TABLE default\n"
  data.each do |dk|
    dk.vtk_legacy_point_data(io: stringio)
    #stringio <<  "\n\n"
  end
  return stringio.string unless options[:io]
end

#to_vtk_legacy_fast(options = {}) ⇒ Object



14
15
16
# File 'lib/graphkit/vtk_legacy_ruby.rb', line 14

def to_vtk_legacy_fast(options={})
  File.open(options[:file_name], 'w'){|file| file.puts to_vtk_legacy}
end

#transpose!Object



475
476
477
478
479
480
481
# File 'lib/graphkit.rb', line 475

def transpose!
  data.each do |datakit|
    datakit.transpose!
  end
  self.xlabel, self.ylabel = ylabel, xlabel
  self.xrange, self.yrange = xrange, yrange
end