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).

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

BQM.from_networkx()
It would be nice to have `BQM.from_networkx()` factory (as a dual to `BQM.to_networkx`).
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)

pip install -e .[all]
parse_log_pytest
requirements.txt
pytest pytest-cov
apt-get update apt-get install -y libboost-dev
3.6
requirements.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
attrs==22.2.0
certifi==2021.5.30
charset-normalizer==2.0.12
codecov==2.1.13
coverage==6.2
Cython==3.0.12
decorator==5.1.1
-e git+https://github.com/dwavesystems/dimod.git@b239e52b628f784ec08b3646ad46243b45f7b60e#egg=dimod
idna==3.10
importlib-metadata==4.8.3
iniconfig==1.1.1
jsonschema==2.6.0
mock==2.0.0
networkx==2.0
numpy==1.15.0
packaging==21.3
pandas==0.22.0
pbr==6.1.1
pluggy==1.0.0
py==1.11.0
pymongo==3.7.1
pyparsing==3.1.4
pytest==7.0.1
pytest-cov==4.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
requests==2.27.1
simplejson==3.16.0
six==1.11.0
tomli==1.2.3
typing_extensions==4.1.1
urllib3==1.26.20
zipp==3.6.0

name: dimod
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=21.2.2=py36h06a4308_0
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - attrs==22.2.0
      - charset-normalizer==2.0.12
      - codecov==2.1.13
      - coverage==6.2
      - cython==3.0.12
      - decorator==5.1.1
      - idna==3.10
      - importlib-metadata==4.8.3
      - iniconfig==1.1.1
      - jsonschema==2.6.0
      - mock==2.0.0
      - networkx==2.0
      - numpy==1.15.0
      - packaging==21.3
      - pandas==0.22.0
      - pbr==6.1.1
      - pluggy==1.0.0
      - py==1.11.0
      - pymongo==3.7.1
      - pyparsing==3.1.4
      - pytest==7.0.1
      - pytest-cov==4.0.0
      - python-dateutil==2.9.0.post0
      - pytz==2025.2
      - requests==2.27.1
      - simplejson==3.16.0
      - six==1.11.0
      - tomli==1.2.3
      - typing-extensions==4.1.1
      - urllib3==1.26.20
      - zipp==3.6.0
prefix: /opt/conda/envs/dimod

tests/test_binary_quadratic_model.py::TestFromNetworkxGraph::test_empty tests/test_binary_quadratic_model.py::TestFromNetworkxGraph::test_functional tests/test_binary_quadratic_model.py::TestFromNetworkxGraph::test_no_biases
tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__contains__ tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__eq__ tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__iter__ tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__len__ tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test__repr__ tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_interaction tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_interaction_counterpart tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_interactions_from tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_offset tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_variable tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_variable_counterpart tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_add_variables_from tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_binary_property tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_binary_property_relabel tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_change_vartype tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_consistency_after_retrieve tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_construction tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_construction_quadratic tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_construction_vartype tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_contract_variables tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_copy tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_fix_variable tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_fix_variables tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_flip_variable tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_normalize tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_normalize_exclusions tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_partial_relabel_copy tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_partial_relabel_inplace tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_pickle_empty tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_pickle_full tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_typical tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_typical_copy tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_typical_inplace tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_with_identity tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_relabel_with_overlap tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_interaction tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_interactions_from tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_offset tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_variable tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_remove_variables_from tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_scale tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_scale_exclusions tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_spin_property tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_spin_property_relabel tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_update tests/test_binary_quadratic_model.py::TestBinaryQuadraticModel::test_variables tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_file_BINARY tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_file_SPIN tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_file_empty_BINARY tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_file_empty_SPIN tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_string_BINARY tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_string_SPIN tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_string_empty_BINARY tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_string_empty_SPIN tests/test_binary_quadratic_model.py::TestConvert::test_coo_functional_two_digit_integers_string tests/test_binary_quadratic_model.py::TestConvert::test_empty tests/test_binary_quadratic_model.py::TestConvert::test_energies_all_ordering tests/test_binary_quadratic_model.py::TestConvert::test_energies_cpp tests/test_binary_quadratic_model.py::TestConvert::test_energies_misordered tests/test_binary_quadratic_model.py::TestConvert::test_from_coo_file tests/test_binary_quadratic_model.py::TestConvert::test_from_coo_string tests/test_binary_quadratic_model.py::TestConvert::test_from_ising tests/test_binary_quadratic_model.py::TestConvert::test_from_numpy_matrix tests/test_binary_quadratic_model.py::TestConvert::test_from_numpy_vectors tests/test_binary_quadratic_model.py::TestConvert::test_from_numpy_vectors_labels tests/test_binary_quadratic_model.py::TestConvert::test_from_qubo tests/test_binary_quadratic_model.py::TestConvert::test_info tests/test_binary_quadratic_model.py::TestConvert::test_to_coo_string_empty_BINARY tests/test_binary_quadratic_model.py::TestConvert::test_to_coo_string_empty_SPIN tests/test_binary_quadratic_model.py::TestConvert::test_to_coo_string_typical_BINARY tests/test_binary_quadratic_model.py::TestConvert::test_to_coo_string_typical_SPIN tests/test_binary_quadratic_model.py::TestConvert::test_to_ising_binary_to_ising tests/test_binary_quadratic_model.py::TestConvert::test_to_ising_spin_to_ising tests/test_binary_quadratic_model.py::TestConvert::test_to_networkx_graph tests/test_binary_quadratic_model.py::TestConvert::test_to_numpy_matrix tests/test_binary_quadratic_model.py::TestConvert::test_to_numpy_vectors tests/test_binary_quadratic_model.py::TestConvert::test_to_numpy_vectors_labels_sorted tests/test_binary_quadratic_model.py::TestConvert::test_to_numpy_vectors_sorted tests/test_binary_quadratic_model.py::TestConvert::test_to_pandas_dataframe tests/test_binary_quadratic_model.py::TestConvert::test_to_qubo_binary_to_qubo tests/test_binary_quadratic_model.py::TestConvert::test_to_qubo_spin_to_qubo tests/test_binary_quadratic_model.py::TestSerialization::test_from_serializable_bytes_empty_v1 tests/test_binary_quadratic_model.py::TestSerialization::test_from_serializable_bytes_empty_v2 tests/test_binary_quadratic_model.py::TestSerialization::test_from_serializable_bytes_v1 tests/test_binary_quadratic_model.py::TestSerialization::test_from_serializable_bytes_v2 tests/test_binary_quadratic_model.py::TestSerialization::test_from_serializable_empty_v1 tests/test_binary_quadratic_model.py::TestSerialization::test_from_serializable_empty_v2 tests/test_binary_quadratic_model.py::TestSerialization::test_from_serializable_v1 tests/test_binary_quadratic_model.py::TestSerialization::test_from_serializable_v2 tests/test_binary_quadratic_model.py::TestSerialization::test_functional tests/test_binary_quadratic_model.py::TestSerialization::test_functional_bytes tests/test_binary_quadratic_model.py::TestSerialization::test_functional_bytes_empty tests/test_binary_quadratic_model.py::TestSerialization::test_functional_bytes_info tests/test_binary_quadratic_model.py::TestSerialization::test_functional_empty tests/test_binary_quadratic_model.py::TestSerialization::test_functional_info tests/test_binary_quadratic_model.py::TestZeroField::test_one_interaction
dimod/binary_quadratic_model.py docs/reference/binary_quadratic_model.rst
dimod/binary_quadratic_model.py docs/reference/binary_quadratic_model.rst