Class: Graph
Constant Summary
collapse
- VERSION =
'1.1.0'
Instance Attribute Summary collapse
Instance Method Summary
collapse
Methods inherited from Hash
#minvert, #t, #transitive, #tsort_each_child
Constructor Details
#initialize ⇒ Graph
Returns a new instance of Graph.
11
12
13
14
15
16
17
|
# File 'lib/graph.rb', line 11
def initialize
super { |h,k| h[k] = [] }
@prefix = []
@order = []
@attribs = Hash.new { |h,k| h[k] = [] }
@edge = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } }
end
|
Instance Attribute Details
#attribs ⇒ Object
Returns the value of attribute attribs.
6
7
8
|
# File 'lib/graph.rb', line 6
def attribs
@attribs
end
|
#edge ⇒ Object
Returns the value of attribute edge.
9
10
11
|
# File 'lib/graph.rb', line 9
def edge
@edge
end
|
#order ⇒ Object
Returns the value of attribute order.
8
9
10
|
# File 'lib/graph.rb', line 8
def order
@order
end
|
#prefix ⇒ Object
Returns the value of attribute prefix.
7
8
9
|
# File 'lib/graph.rb', line 7
def prefix
@prefix
end
|
Instance Method Details
#[]=(key, val) ⇒ Object
19
20
21
22
|
# File 'lib/graph.rb', line 19
def []= key, val
@order << key unless self.has_key? key
super
end
|
#counts ⇒ Object
52
53
54
55
56
57
58
|
# File 'lib/graph.rb', line 52
def counts
result = Hash.new 0
each_pair do |from, to|
result[from] += 1
end
result
end
|
#delete(key) ⇒ Object
24
25
26
27
|
# File 'lib/graph.rb', line 24
def delete key
@order.delete key
super
end
|
#each_pair ⇒ Object
36
37
38
39
40
41
42
|
# File 'lib/graph.rb', line 36
def each_pair
@order.each do |from|
self[from].each do |to|
yield from, to
end
end
end
|
#filter_size(minimum) ⇒ Object
29
30
31
32
33
34
|
# File 'lib/graph.rb', line 29
def filter_size minimum
counts.each do |node, count|
next unless count < minimum
delete node
end
end
|
#invert ⇒ Object
44
45
46
47
48
49
50
|
# File 'lib/graph.rb', line 44
def invert
result = self.class.new
each_pair do |from, to|
result[to] << from
end
result
end
|
#keys_by_count ⇒ Object
60
61
62
|
# File 'lib/graph.rb', line 60
def keys_by_count
counts.sort_by { |key, count| -count }.map {|key, count| key }
end
|
#save(path, type = "png") ⇒ Object
87
88
89
90
91
92
|
# File 'lib/graph.rb', line 87
def save path, type="png"
File.open "#{path}.dot", "w" do |f|
f.write self.to_s
end
system "dot -T#{type} #{path}.dot > #{path}.#{type}" if type
end
|
#to_s ⇒ Object
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
# File 'lib/graph.rb', line 64
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
|