Class: Newral::Graphs::Graph

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nodes: [], edges: []) ⇒ Graph

Returns a new instance of Graph.



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

def initialize( nodes: [], edges: [] )
  @nodes = nodes
  @edges = edges
end

Instance Attribute Details

#edgesObject (readonly)

Returns the value of attribute edges.



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

def edges
  @edges
end

#nodesObject (readonly)

Returns the value of attribute nodes.



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

def nodes
  @nodes
end

Instance Method Details

#add_edge(edge) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/newral/graphs/graph.rb', line 13

def add_edge( edge )
  unless @nodes.member?( edge.start_node ) && @nodes.member?( edge.end_node )
    # let´s try to find it 
    @nodes.each do |node|
      edge.start_node = node if node.respond_to?( :name ) && node.name == edge.start_node
      edge.end_node = node if node.respond_to?( :name ) && node.name == edge.end_node
    end 
    raise Errors::UnkownNode unless @nodes.member?( edge.start_node ) && @nodes.member?( edge.end_node )
  end
  @edges << edge 
  self
end

#add_edges(edges, directed: false) ⇒ Object

we can add also like this {1=> 2, 2 => 5 }



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/newral/graphs/graph.rb', line 41

def add_edges( edges, directed: false )
  if edges.kind_of?( Hash )
    edges.each do |from,to|
      @edges << Edge.new( start_node: from, end_node: to, directed: directed )
    end 
  else 
    edges.each do |edge|
      add_edge edge
    end
  end
  self
end

#add_node(node) ⇒ Object



26
27
28
29
# File 'lib/newral/graphs/graph.rb', line 26

def add_node( node )
  @nodes < node 
  self
end

#add_nodes(nodes) ⇒ Object



31
32
33
34
# File 'lib/newral/graphs/graph.rb', line 31

def add_nodes( nodes )
  @nodes = @nodes+nodes
  self
end

#find_edges(node) ⇒ Object



54
55
56
57
58
59
# File 'lib/newral/graphs/graph.rb', line 54

def find_edges( node )
  @edges.collect do |edge| 
    keep = edge.directed ? edge.start_node == node : edge.start_node == node || edge.end_node == node
    edge if keep
  end.compact
end

#find_node_by_name(name) ⇒ Object



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

def find_node_by_name( name )
  @nodes.find{ |node| node.name == name }
end