Browse Source

Fix GraphState.to_json() for tuple-like nodes

master
Pete Shadbolt 8 years ago
parent
commit
4646554779
4 changed files with 38 additions and 11 deletions
  1. +1
    -1
      abp/fancy.py
  2. +14
    -3
      abp/graphstate.py
  3. +14
    -0
      abp/util.py
  4. +9
    -7
      tests/test_json.py

+ 1
- 1
abp/fancy.py View File

@@ -39,7 +39,7 @@ class GraphState(graphstate.GraphState, networkx.Graph):

# Send data to browser and rate-limit
try:
self.ws.send(json.dumps(self.to_json(), default = str))
self.ws.send(json.dumps(self.to_json(stringify=True)))
self.ws.recv()
time.sleep(delay)
except websocket._exceptions.WebSocketTimeoutException:


+ 14
- 3
abp/graphstate.py View File

@@ -6,6 +6,7 @@ import itertools as it
import json
import qi, clifford, util
import random
from util import ABPJsonEncoder


class GraphState(object):
@@ -177,9 +178,19 @@ class GraphState(object):
nbstr = str(self.adj)
return "graph:\n node: {}\n adj: {}\n".format(node, nbstr)

def to_json(self):
""" Convert the graph to JSON form """
return {"node": self.node, "adj": self.adj}
def to_json(self, stringify = False):
"""
Convert the graph to JSON form.
JSON keys must be strings, But sometimes it is useful to have
a JSON-like object whose keys are tuples!
"""
if stringify:
node = {str(key):value for key, value in self.node.items()}
adj = {str(key): {str(key):value for key, value in ngbh.items()}
for key, ngbh in self.adj.items()}
return {"node": node, "adj": adj}
else:
return {"node": self.node, "adj": self.adj}

def from_json(self, data):
""" Reconstruct from JSON """


+ 14
- 0
abp/util.py View File

@@ -2,5 +2,19 @@
Utility functions for ABP
"""

import json

def xyz(x, y, z=0):
return {"x": x, "y": y, "z": z}

class ABPJsonEncoder(json.JSONEncoder):
def default(self, thing):
print thing

if __name__ == '__main__':
j = ABPJsonEncoder()
print j.encode({1:2})
j = ABPJsonEncoder()
print j.encode({1:2})
print j.encode({(1,2):2})


+ 9
- 7
tests/test_json.py View File

@@ -1,4 +1,4 @@
from abp import GraphState
from abp import GraphState, fancy
from abp import clifford
from demograph import demograph
import time
@@ -12,11 +12,13 @@ def test_json_basic():
assert "node" in js
e = GraphState()

#TODO
def _test_to_json():
""" Nah """
assert e != g
e.from_json(js)
assert e == g
def test_tuple_keys():
""" Test that we can write tuple-ish keys """
g = fancy.GraphState()
g.add_node("string")
g.add_node((1, 2, 3))
g.add_edge((1, 2, 3), "string")
print json.dumps(g.to_json(True))




Loading…
Cancel
Save