Class: Graph

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGraph

Returns a new instance of Graph.



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

def initialize
  super { |h,k| h[k] = [] }
  @prefix = []
  @attribs = Hash.new { |h,k| h[k] = [] }
  @edge = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } }
  @order = []
end

Instance Attribute Details

#attribsObject (readonly)

Returns the value of attribute attribs.



5
6
7
# File 'lib/graph.rb', line 5

def attribs
  @attribs
end

#edgeObject (readonly)

Returns the value of attribute edge.



8
9
10
# File 'lib/graph.rb', line 8

def edge
  @edge
end

#orderObject (readonly)

Returns the value of attribute order.



7
8
9
# File 'lib/graph.rb', line 7

def order
  @order
end

#prefixObject (readonly)

Returns the value of attribute prefix.



6
7
8
# File 'lib/graph.rb', line 6

def prefix
  @prefix
end

Instance Method Details

#[]=(key, val) ⇒ Object



18
19
20
21
# File 'lib/graph.rb', line 18

def []=(key, val)
  @order << key unless self.has_key? key
  super(key, val)
end

#countsObject



39
40
41
42
43
44
45
# File 'lib/graph.rb', line 39

def counts
  result = Hash.new(0)
  each_pair do |from, to|
    result[from] += 1
  end
  result
end

#each_pairObject



23
24
25
26
27
28
29
# File 'lib/graph.rb', line 23

def each_pair
  @order.each do |from|
    self[from].each do |to|
      yield(from, to)
    end
  end
end

#invertObject



31
32
33
34
35
36
37
# File 'lib/graph.rb', line 31

def invert
  result = self.class.new
  each_pair do |from, to|
    result[to] << from
  end
  result
end

#keys_by_countObject



47
48
49
# File 'lib/graph.rb', line 47

def keys_by_count
  counts.sort_by { |x,y| y }.map {|x| x.first }
end

#save(path, type = "png") ⇒ Object



70
71
72
73
74
75
76
77
# File 'lib/graph.rb', line 70

def save(path, type="png")
  File.open(path + ".dot", "w") do |f|
    f.puts self.to_s
    f.flush
    cmd = "/usr/local/bin/dot -T#{type} #{path}.dot > #{path}.#{type}"
    system cmd
  end
end

#to_sObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/graph.rb', line 51

def to_s
  result = []
  result << "digraph absent"
  result << "  {"
  @prefix.each do |line|
    result << line
  end
  @attribs.sort.each do |node, attribs|
    result << "    #{node.inspect} [ #{attribs.join(',')} ]"
  end
  each_pair do |from, to|
    edge = @edge[from][to].join(", ")
    edge = " [ #{edge} ]" unless edge.empty?
    result << "    #{from.inspect} -> #{to.inspect}#{edge};"
  end
  result << "  }"
  result.join("\n")
end