From d6b5f540df6908b5b924db9186aa70d3dec34201 Mon Sep 17 00:00:00 2001 From: Pete Shadbolt Date: Thu, 3 Nov 2016 18:44:01 +0000 Subject: [PATCH] Add & test GraphState.from_json We needed to implement `GraphState.from_json` so that the server can track a copy of the client's state. That's a useful byproduct of this work! --- abp/graphstate.py | 10 +++++++--- bin/abpserver | 1 + tests/test_json.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 tests/test_json.py diff --git a/abp/graphstate.py b/abp/graphstate.py index f443e0d..1444fc2 100644 --- a/abp/graphstate.py +++ b/abp/graphstate.py @@ -405,9 +405,6 @@ class GraphState(object): >>> with open("graph.json") as f: json.dump(graph.to_json(True), f) - .. todo:: - Implement ``from_json()``! - """ if stringify: node = {str(key): value for key, value in self.node.items()} @@ -417,6 +414,13 @@ class GraphState(object): else: return {"node": self.node, "adj": self.adj} + def from_json(self, data): + """ Construct the graph from JSON data + :param data: JSON data to be read. + """ + self.node = data["node"] + self.adj = data["adj"] + def to_state_vector(self): """ Get the full state vector corresponding to this stabilizer state. Useful for debugging, interface with other simulators. This method becomes very slow for more than about ten qubits! diff --git a/bin/abpserver b/bin/abpserver index 48d10d0..08069e1 100755 --- a/bin/abpserver +++ b/bin/abpserver @@ -16,6 +16,7 @@ import json from pkg_resources import resource_filename clients = [] +local_state = abp.GraphState() def new_message(client, server, message): if message.startswith("edit:"): diff --git a/tests/test_json.py b/tests/test_json.py new file mode 100644 index 0000000..9c0053b --- /dev/null +++ b/tests/test_json.py @@ -0,0 +1,31 @@ +import mock +import abp + +def test_json(): + """ Test to_json and from_json """ + a = mock.named_node_graph() + j = a.to_json() + + b = abp.GraphState() + b.from_json(j) + assert a == b + + +def test_json_again(): + """ Test to_json and from_json """ + # Make a random graph + a = abp.GraphState(10) + a.act_circuit(mock.random_graph_circuit()) + + # Dump it to JSON + j = a.to_json() + + # Reconstruct from JSON + b = abp.GraphState() + b.from_json(j) + + # Check equality + assert a == b + + +