Class: GraphKit

Inherits:
KitHash show all
Includes:
Writer, 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

Modules: Writer Classes: AxisKit, DataError, DataKit, GnuplotPlotOptions, GnuplotSetOptions, GnuplotVariables, MultiKit

Constant Summary collapse

MultiWindow =

Backwards compatibility

MultiKit
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 Writer

#gnuplot_write

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



326
327
328
329
330
331
332
333
# File 'lib/graphkit.rb', line 326

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.



357
358
359
360
# File 'lib/graphkit.rb', line 357

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

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



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'lib/graphkit/gnuplot.rb', line 534

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

\\pagestyle{empty}
\\begin{document}
\\begin{figure}
EOF

	figure_postamble = options[:postamble] || <<EOF
\\end{figure}
\\end{document}
EOF
	text = <<EOF
#{figure_preamble}
#{yield}
#{figure_postamble}
EOF
		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.



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

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.



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

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



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
277
278
279
280
281
# File 'lib/graphkit/gnuplot.rb', line 252

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)



396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/graphkit.rb', line 396

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.



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/graphkit.rb', line 413

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



349
350
351
352
353
354
355
356
357
358
359
# File 'lib/graphkit/gnuplot.rb', line 349

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



507
508
509
510
511
512
513
514
515
516
# File 'lib/graphkit.rb', line 507

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]])



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

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.



447
448
449
450
451
# File 'lib/graphkit.rb', line 447

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

#each_axiskit(*axes, &block) ⇒ Object



477
478
479
480
481
482
483
484
# File 'lib/graphkit.rb', line 477

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



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

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



304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/graphkit/gnuplot.rb', line 304

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



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

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



245
246
247
# File 'lib/graphkit/gnuplot.rb', line 245

def gnuplot_variables
	@gnuplot_variables ||= GnuplotVariables.new
end

#lx(*args) ⇒ Object

:nodoc:



363
364
365
# File 'lib/graphkit.rb', line 363

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

#lx=(val) ⇒ Object

:nodoc: (deprecated)



367
368
369
# File 'lib/graphkit.rb', line 367

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

#plot_area_sizeObject



486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/graphkit.rb', line 486

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



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

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 << <<EOF
# vtk DataFile Version 3.0
vtk output
ASCII
DATASET UNSTRUCTURED_GRID
POINTS #{npoints} float
EOF
	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 << <<EOF

CELLS #{ncells} #{ncell_elements}
EOF
	stringio << cellstring
	stringio << <<EOF

CELL_TYPES #{ncells}
EOF
	data.each do |dk|
		dk.vtk_legacy_cell_types(io: stringio)
		#stringio <<  "\n\n"
	end
	stringio << <<EOF

POINT_DATA #{npoints} 
SCALARS myvals float
LOOKUP_TABLE default
EOF
	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



499
500
501
502
503
504
505
# File 'lib/graphkit.rb', line 499

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