Class: JSONToNetworkGraph

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

Instance Method Summary collapse

Constructor Details

#initialize(input, field1, field2) ⇒ JSONToNetworkGraph

Returns a new instance of JSONToNetworkGraph.



7
8
9
10
11
12
13
14
# File 'lib/jsontonetworkgraph.rb', line 7

def initialize(input, field1, field2)
  @input = JSON.parse(input)
  @field1 = field1
  @field2 = field2
  @nodehash = Hash.new
  @linkhash = Hash.new
  @nodeindex = 0
end

Instance Method Details

#addupdateNode(fieldname, i) ⇒ Object

Create or update the appropriate node



25
26
27
28
29
30
31
32
# File 'lib/jsontonetworkgraph.rb', line 25

def addupdateNode(fieldname, i)
  if !(@nodehash.include? i[fieldname])
    @nodehash[i[fieldname]] = Node.new(@nodeindex, i[fieldname], fieldname, i)
    @nodeindex += 1
  else
    @nodehash[i[fieldname]].update(i)
  end
end

#genJSONObject

Generate JSON with nodes and links



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/jsontonetworkgraph.rb', line 66

def genJSON
  genNodes
  genLinks
  linkCount
  
  nodearray = Array.new
  @nodehash.each_value do |n|
    nodearray.push(n.nodeData)
  end

  linkarray = Array.new
  @linkhash.each_value do |l|
    linkarray.push(l.linkData)
  end

  jsonhash = {:nodes => nodearray, :links => linkarray}
  JSON.pretty_generate(jsonhash)
end

Generate all the links



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/jsontonetworkgraph.rb', line 35

def genLinks
  @input.each do |i|
    identifier = i[@field1]+ "-" + i[@field2]
    if !@linkhash.include? identifier
      source = @nodehash[i[@field1]].getID
      target = @nodehash[i[@field2]].getID

      @nodehash[i[@field1]].addLink
      @nodehash[i[@field2]].addLink

      @linkhash[identifier] = Link.new(source, target, i[@field1], i[@field2], i)
    else
      @linkhash[identifier].update(i)
    end
  end
end

#genNodesObject

Generate all the nodes



17
18
19
20
21
22
# File 'lib/jsontonetworkgraph.rb', line 17

def genNodes
  @input.each do |i|
    addupdateNode(@field1, i)
    addupdateNode(@field2, i)
  end
end

#linkCountObject



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/jsontonetworkgraph.rb', line 52

def linkCount
  @linkhash.each_value do |l|
    count1 = @nodehash[l.instance_variable_get(:@field1)].instance_variable_get(:@linkcount)
    count2 = @nodehash[l.instance_variable_get(:@field2)].instance_variable_get(:@linkcount)

    if count1 > count2
      l.linkCount(count2)
    else
      l.linkCount(count1)
    end
  end
end