From 577e9177320c39029c639d59f28894c40125209b Mon Sep 17 00:00:00 2001 From: Pete Shadbolt Date: Mon, 22 Aug 2016 14:42:58 +0100 Subject: [PATCH] More convenient networkx -> abp conversion Now you can write `abp.fancy.GraphState(nx.Graph())`. TODO: make this work for a non-fancy `GraphState` --- abp/fancy.py | 3 ++- tests/test_fancy.py | 17 ++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/abp/fancy.py b/abp/fancy.py index 25b1f87..32ea3b2 100644 --- a/abp/fancy.py +++ b/abp/fancy.py @@ -10,7 +10,8 @@ import util class GraphState(graphstate.GraphState, nx.Graph): def __init__(self, *args, **kwargs): - if type(args[0])==nx.Graph: + if args and type(args[0]) == nx.Graph: + graphstate.GraphState.__init__(self) self.from_nx(args[0]) else: graphstate.GraphState.__init__(self, *args, **kwargs) diff --git a/tests/test_fancy.py b/tests/test_fancy.py index dcc6884..636eecf 100644 --- a/tests/test_fancy.py +++ b/tests/test_fancy.py @@ -5,6 +5,7 @@ from abp import clifford from abp.util import xyz from mock import simple_graph + def test_json_basic(): """ Test that we can export to JSON """ g = simple_graph() @@ -12,6 +13,7 @@ def test_json_basic(): assert "adj" in js assert "node" in js + def test_tuple_keys(): """ Test that we can use tuple-ish keys """ g = fancy.GraphState() @@ -20,17 +22,22 @@ def test_tuple_keys(): g.add_edge((1, 2, 3), "string") json.dumps(g.to_json(True)) + def networkx_test(): """ Test that fancy graph states really behave like networkx graphs """ g = fancy.GraphState() - g.add_qubit(0, position = xyz(10, 0, 0)) - g.add_qubit(1, position = xyz(1, 0, 0)) + g.add_qubit(0, position=xyz(10, 0, 0)) + g.add_qubit(1, position=xyz(1, 0, 0)) g.act_hadamard(0) g.act_hadamard(1) g.act_cz(0, 1) g.copy() - # TODO: more tests here! - - +def test_from_nx(): + """ Test that making graphs from networkx objects goes smoothly """ + g = nx.random_geometric_graph(100, 2) + psi = fancy.GraphState(g) + assert psi.node[0]["vop"] == 0 + assert len(psi.edges()) > 0 + psi.measure(0, "px", detail=True)