From 77c89ab5453c05e83dcb2cf21214d754cf7e3b73 Mon Sep 17 00:00:00 2001 From: JunkaiWang-TheoPhy <1181100960@qq.com> Date: Mon, 30 Nov 2026 19:49:44 +0800 Subject: [PATCH] Preserve isolated detectors and boundary nodes when exporting to NetworkX --- src/pymatching/matching.py | 1 + tests/matching/output_graph_test.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/pymatching/matching.py b/src/pymatching/matching.py index 3ac8fed0e..f64247967 100644 --- a/src/pymatching/matching.py +++ b/src/pymatching/matching.py @@ -1678,6 +1678,7 @@ def to_networkx(self) -> nx.Graph: has_virtual_boundary = True else: graph.add_edge(u, v, **data) + graph.add_nodes_from(range(num_nodes)) boundary = self.boundary for i in graph.nodes: is_boundary = i in boundary diff --git a/tests/matching/output_graph_test.py b/tests/matching/output_graph_test.py index 98a60badf..3c655e9e0 100644 --- a/tests/matching/output_graph_test.py +++ b/tests/matching/output_graph_test.py @@ -123,3 +123,18 @@ def test_self_loop_to_networkx(): assert list(g.edges(data=True)) == [(0, 0, {'fault_ids': set(), 'weight': 3.0, 'error_probability': -1.0}), (1, 1, {'fault_ids': set(), 'weight': 2.0, 'error_probability': -1.0}), (1, 2, {'fault_ids': set(), 'weight': 1.0, 'error_probability': -1.0})] + + +def test_networkx_roundtrip_with_isolated_nodes(): + graph = nx.Graph() + graph.add_nodes_from(range(4)) + graph.add_edge(0, 1) + graph.nodes[3]['is_boundary'] = True + original = Matching(graph) + exported = original.to_networkx() + assert set(nx.isolates(exported)) == {2, 3} + assert exported.nodes[2]['is_boundary'] is False + assert exported.nodes[3]['is_boundary'] is True + restored = Matching(exported) + assert restored.num_detectors == original.num_detectors + assert restored.boundary == original.boundary