Anders and Briegel in Python
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.7KB

  1. import networkx as nx
  2. from matplotlib import pyplot as plt
  3. vop_colors = ["red", "green", "blue"]
  4. def graph(n):
  5. """ Generate a graph with Hadamards on each qubit """
  6. graph = [set() for i in xrange(n)]
  7. vops = [0 for i in xrange(n)]
  8. return graph, vops
  9. def add_edge(graph, v1, v2):
  10. """ Add an edge between two vertices in the graph """
  11. graph[v1].add(v2)
  12. graph[v2].add(v1)
  13. def del_edge(graph, v1, v2):
  14. """ Delete an edge between two vertices in the graph """
  15. graph[v1].remove(v2)
  16. graph[v2].remove(v1)
  17. def has_edge(graph, v1, v2):
  18. """ Test existence of an edge between two vertices in the graph """
  19. return v2 in graph[v1]
  20. def toggle_edge(graph, v1, v2):
  21. """ Toggle an edge between two vertices in the graph """
  22. if has_edge(graph, v1, v2):
  23. del_edge(graph, v1, v2)
  24. else:
  25. add_edge(graph, v1, v2)
  26. def edgelist(graph):
  27. """ Describe a graph as an edgelist """
  28. edges = frozenset(frozenset((i, n))
  29. for i, v in enumerate(graph)
  30. for n in v)
  31. return [tuple(e) for e in edges]
  32. def draw(graph, vops, filename="out.pdf", ns=500):
  33. """ Draw a graph with networkx layout """
  34. g = nx.from_edgelist(edgelist(graph))
  35. pos = nx.spring_layout(g)
  36. colors = [vop_colors[vop] for vop in vops]
  37. nx.draw_networkx_nodes(g, pos, node_color="white", node_size=ns)
  38. nx.draw_networkx_nodes(g, pos, node_color=colors, node_size=ns, alpha=.4)
  39. nx.draw_networkx_labels(g, pos)
  40. nx.draw_networkx_edges(g, pos)
  41. plt.axis('off')
  42. plt.savefig(filename)
  43. if __name__ == '__main__':
  44. g, vops = graph(10)
  45. add_edge(g, 0, 1)
  46. add_edge(g, 1, 3)
  47. add_edge(g, 3, 2)
  48. add_edge(g, 3, 0)
  49. add_edge(g, 2, 0)
  50. edgelist(g)
  51. draw(g, vops)