Method: NetworkX::DiGraph#subgraph

Defined in:
lib/networkx/digraph.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



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/networkx/digraph.rb', line 186

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

      sub_graph.add_node(u, **@nodes[u])
      @adj[u].each do |v, uv_attrs|
        sub_graph.add_edge(u, v, **uv_attrs) 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