Class: Graph

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv) ⇒ Graph

Returns a new instance of Graph.

Raises:

  • (Exception)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rgraph/graph.rb', line 9

def initialize(csv)
  @nodes = []
  @links = []
  raise Exception.new("the file must be a .csv") unless File.extname(csv) == ".csv"

  CSV.foreach(csv, headers: true) do |row|
    #last because CSV#delete returns [column,value]
    source_id = row.delete('source').last
    target_id = row.delete('target').last

    unless source = get_node_by_id(source_id)
      source = Node.new(id: source_id)
      @nodes << source
    end
    unless target = get_node_by_id(target_id)
      target = Node.new(id: target_id)
      @nodes << target
    end

    @links << Link.new(source: source, target: target, weight: row['weight'], year: row['year'])
  end
end

Instance Attribute Details

Returns the value of attribute links.



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

def links
  @links
end

#nodesObject

Returns the value of attribute nodes.



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

def nodes
  @nodes
end

Instance Method Details

#average_degreeObject



44
45
46
# File 'lib/rgraph/graph.rb', line 44

def average_degree
  degrees.inject(:+) / @nodes.size.to_f
end

#cumulative_degreeObject



48
49
50
51
52
53
54
55
56
# File 'lib/rgraph/graph.rb', line 48

def cumulative_degree
  cached_degrees = degrees
  cum = []

  0.upto(degrees.max - 1) do |i|
    cum[i] = cached_degrees.select{|degree| degree > i}.count
  end
  cum.map{|a| a / cum.max.to_f}
end

#degreesObject



40
41
42
# File 'lib/rgraph/graph.rb', line 40

def degrees
  @nodes.map{|node| node.degree}
end


36
37
38
# File 'lib/rgraph/graph.rb', line 36

def each_link(&block)
  @links.each(&block)
end

#each_node(&block) ⇒ Object



32
33
34
# File 'lib/rgraph/graph.rb', line 32

def each_node(&block)
  @nodes.each(&block)
end