Repository: dwavesystems/dimod

Issue:
BQM.from_networkx()
It would be nice to have `BQM.from_networkx()` factory (as a dual to `BQM.to_networkx`).

Discussion:
codecov-io: # [Codecov](https://codecov.io/gh/dwavesystems/dimod/pull/448?src=pr&el=h1) Report
> Merging [#448](https://codecov.io/gh/dwavesystems/dimod/pull/448?src=pr&el=desc) into [master](https://codecov.io/gh/dwavesystems/dimod/commit/b239e52b628f784ec08b3646ad46243b45f7b60e?src=pr&el=desc) will **decrease** coverage by `0.04%`.
> The diff coverage is `81.81%`.

[![Impacted file tree graph](https://codecov.io/gh/dwavesystems/dimod/pull/448/graphs/tree.svg?width=650&token=KyxipO4fvT&height=150&src=pr)](https://codecov.io/gh/dwavesystems/dimod/pull/448?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master     #448      +/-   ##
==========================================
- Coverage   93.13%   93.09%   -0.05%     
==========================================
  Files          47       47              
  Lines        3087     3098      +11     
==========================================
+ Hits         2875     2884       +9     
- Misses        212      214       +2
```


| [Impacted Files](https://codecov.io/gh/dwavesystems/dimod/pull/448?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [dimod/binary\_quadratic\_model.py](https://codecov.io/gh/dwavesystems/dimod/pull/448/diff?src=pr&el=tree#diff-ZGltb2QvYmluYXJ5X3F1YWRyYXRpY19tb2RlbC5weQ==) | `95.49% <81.81%> (-0.25%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/dwavesystems/dimod/pull/448?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/dwavesystems/dimod/pull/448?src=pr&el=footer). Last update [b239e52...07722df](https://codecov.io/gh/dwavesystems/dimod/pull/448?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/dimod/binary_quadratic_model.py b/dimod/binary_quadratic_model.py
index 672ee375..a8895ba2 100644
--- a/dimod/binary_quadratic_model.py
+++ b/dimod/binary_quadratic_model.py
@@ -1851,9 +1851,10 @@ class BinaryQuadraticModel(abc.Sized, abc.Container, abc.Iterable):
         """Convert a binary quadratic model to NetworkX graph format.
 
         Args:
-            node_attribute_name (hashable):
+            node_attribute_name (hashable, optional, default='bias'):
                 Attribute name for linear biases.
-            edge_attribute_name (hashable):
+
+            edge_attribute_name (hashable, optional, default='bias'):
                 Attribute name for quadratic biases.
 
         Returns:
@@ -1896,6 +1897,62 @@ class BinaryQuadraticModel(abc.Sized, abc.Container, abc.Iterable):
 
         return BQM
 
+    @classmethod
+    def from_networkx_graph(cls, G, vartype=None, node_attribute_name='bias',
+                            edge_attribute_name='bias'):
+        """Create a binary quadratic model from a NetworkX graph.
+
+        Args:
+            G (:obj:`networkx.Graph`):
+                A NetworkX graph with biases stored as node/edge attributes.
+
+            vartype (:class:`.Vartype`/str/set, optional):
+                Variable type for the binary quadratic model. Accepted input
+                values:
+
+                * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``
+                * :class:`.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.
+
+        Returns:
+            :obj:`.BinaryQuadraticModel`
+
+        Examples:
+
+            >>> import networkx as nx
+            ...
+            >>> G = nx.Graph()
+            >>> G.add_node('a', bias=.5)
+            >>> G.add_edge('a', 'b', bias=-1)
+            >>> bqm = dimod.BinaryQuadraticModel.from_networkx_graph(G, 'SPIN')
+            >>> bqm.adj['a']['b']
+            -1
+
+        """
+        if vartype is None:
+            if not hasattr(G, 'vartype'):
+                msg = ("either 'vartype' argument must be provided or "
+                       "the given graph should have a vartype attribute.")
+                raise ValueError(msg)
+            vartype = G.vartype
+
+        linear = G.nodes(data=node_attribute_name, default=0)
+        quadratic = G.edges(data=edge_attribute_name, default=0)
+        offset = getattr(G, 'offset', 0)
+
+        return cls(linear, quadratic, offset, vartype)
+
     def to_ising(self):
         """Converts a binary quadratic model to Ising format.
 
diff --git a/docs/reference/binary_quadratic_model.rst b/docs/reference/binary_quadratic_model.rst
index 6784902d..cb02c08a 100644
--- a/docs/reference/binary_quadratic_model.rst
+++ b/docs/reference/binary_quadratic_model.rst
@@ -98,6 +98,7 @@ Converting to and from other formats
 
    BinaryQuadraticModel.from_coo
    BinaryQuadraticModel.from_ising
+   BinaryQuadraticModel.from_networkx_graph
    BinaryQuadraticModel.from_numpy_matrix
    BinaryQuadraticModel.from_numpy_vectors
    BinaryQuadraticModel.from_qubo


Test patch:
diff --git a/tests/test_binary_quadratic_model.py b/tests/test_binary_quadratic_model.py
index 8790d161..d0c212a9 100644
--- a/tests/test_binary_quadratic_model.py
+++ b/tests/test_binary_quadratic_model.py
@@ -2157,3 +2157,32 @@ class TestZeroField(unittest.TestCase):
         self.assertEqual(bqm.adj, {'a': {'b': -1}, 'b': {'a': -1}})
         self.assertEqual(set(bqm.linear.keys()), {'a', 'b'})
         self.assertEqual(set(bqm.linear.items()), {('a', 0), ('b', 0)})
+
+
+@unittest.skipUnless(_networkx, "NetworkX is not installed")
+class TestFromNetworkxGraph(unittest.TestCase):
+    def test_empty(self):
+        G = nx.Graph()
+        G.vartype = 'SPIN'
+        bqm = dimod.BinaryQuadraticModel.from_networkx_graph(G)
+        self.assertEqual(len(bqm), 0)
+        self.assertIs(bqm.vartype, dimod.SPIN)
+
+    def test_no_biases(self):
+        G = nx.complete_graph(5)
+        G.vartype = 'BINARY'
+        bqm = dimod.BinaryQuadraticModel.from_networkx_graph(G)
+
+        self.assertIs(bqm.vartype, dimod.BINARY)
+        self.assertEqual(set(bqm.variables), set(range(5)))
+        for u, v in itertools.combinations(range(5), 2):
+            self.assertEqual(bqm.adj[u][v], 0)
+            self.assertEqual(bqm.linear[v], 0)
+        self.assertEqual(len(bqm.quadratic), len(G.edges))
+
+    def test_functional(self):
+        bqm = dimod.BinaryQuadraticModel.from_ising({'a': .5},
+                                                    {'bc': 1, 'cd': -4},
+                                                    offset=6)
+        new = dimod.BinaryQuadraticModel.from_networkx_graph(bqm.to_networkx_graph())
+        self.assertEqual(bqm, new)