Method: NetworkX::MultiDiGraph#subgraph

Defined in:
lib/networkx/multidigraph.rb

#subgraph(nodes) ⇒ Object

Returns subgraph consisting of given array of nodes

Examples:

graph.subgraph(%w[Mumbai Nagpur])


201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/networkx/multidigraph.rb', line 201

def subgraph(nodes)
  case nodes
  when Array, Set
    sub_graph = NetworkX::MultiDiGraph.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|
        edge_val.each { |_, keyval| sub_graph.add_edge(u, v, **keyval) 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