Method: NetworkX::Graph#subgraph

Defined in:
lib/networkx/graph.rb

#subgraph(nodes) ⇒ Object

Returns subgraph consisting of given array of nodes

Examples:

graph.subgraph(%w[Mumbai Nagpur])

Parameters:

  • nodes (Array<Object>)

    the nodes to be included in the subgraph



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/networkx/graph.rb', line 377

def subgraph(nodes)
  case nodes
  when Array, Set
    sub_graph = NetworkX::Graph.new(**@graph)
    nodes.each do |u, _|
      raise KeyError, "#{u} does not exist in the current graph!" unless @nodes.has_key?(u)

      sub_graph.add_node(u, **@nodes[u])
      @adj[u].each do |v, edge_val|
        sub_graph.add_edge(u, v, **edge_val) if @adj[u].has_key?(v) && nodes.include?(v)
      end
    end
    sub_graph
  else
    raise ArgumentError, 'Expected Argument to be Array or Set of nodes, ' \
                         "received #{nodes.class.name} instead."
  end
end