dimod.from_networkx_graph

from_networkx_graph(G, vartype=None, node_attribute_name='bias', edge_attribute_name='bias', cls=None, dtype=<class 'object'>)[source]

Create a binary quadratic model from a NetworkX graph.

Parameters
  • G (networkx.Graph) – A NetworkX graph with biases stored as node/edge attributes.

  • vartype (Vartype/str/set, optional) –

    Variable type for the binary quadratic model. Accepted input values:

    • Vartype.SPIN, 'SPIN', {-1, 1}

    • Vartype.BINARY, 'BINARY', {0, 1}

    If not provided, the G should have a vartype attribute. If vartype is provided and G.vartype exists then the argument overrides the property.

  • node_attribute_name (hashable, optional, default='bias') – Attribute name for linear biases. If the node does not have a matching attribute then the bias defaults to 0.

  • edge_attribute_name (hashable, optional, default='bias') – Attribute name for quadratic biases. If the edge does not have a matching attribute then the bias defaults to 0.

  • dtype – The dtype of the binary quadratic model. Defaults to object.

Returns

A binary quadratic model of type cls.

Examples

This example creates a BQM from an illustrative NetworkX graph.

>>> import networkx as nx
>>> import random
...
>>> G = nx.generators.complete_graph(4)
>>> for node in G.nodes:
...     G.nodes[node]['bias'] = random.choice([1,-1])
>>> for edge in G.edges:
...     G.edges[edge]['quadratic'] = random.choice([1,-1])
...
>>> bqm = dimod.from_networkx_graph(G,
...                                 vartype='BINARY',
...                                 edge_attribute_name='quadratic')