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.

182 lines
6.0KB

  1. """
  2. Provides an extremely basic graph structure, based on neighbour lists
  3. """
  4. from collections import defaultdict
  5. import itertools as it
  6. import clifford
  7. import json
  8. try:
  9. import networkx as nx
  10. except ImportError:
  11. print "Could not import networkx: layout will not work"
  12. class GraphState(object):
  13. def __init__(self):
  14. self.ngbh = defaultdict(set)
  15. self.vops = defaultdict(int)
  16. self.meta = defaultdict(dict)
  17. def add_vertex(self, v):
  18. """ Add a vertex if it doesn't already exist """
  19. if not v in self.ngbh:
  20. self.ngbh[v] = set()
  21. self.vops[v] = clifford.by_name["hadamard"]
  22. def add_edge(self, v1, v2):
  23. """ Add an edge between two vertices in the self """
  24. if not v1 in self.ngbh:
  25. self.vops[v1] = clifford.by_name["hadamard"]
  26. if not v2 in self.ngbh:
  27. self.vops[v2] = clifford.by_name["hadamard"]
  28. self.ngbh[v1].add(v2)
  29. self.ngbh[v2].add(v1)
  30. def del_edge(self, v1, v2):
  31. """ Delete an edge between two vertices in the self """
  32. self.ngbh[v1].remove(v2)
  33. self.ngbh[v2].remove(v1)
  34. def has_edge(self, v1, v2):
  35. """ Test existence of an edge between two vertices in the self """
  36. return v2 in self.ngbh[v1]
  37. def toggle_edge(self, v1, v2):
  38. """ Toggle an edge between two vertices in the self """
  39. if self.has_edge(v1, v2):
  40. self.del_edge(v1, v2)
  41. else:
  42. self.add_edge(v1, v2)
  43. def edgelist(self):
  44. """ Describe a graph as an edgelist """
  45. edges = frozenset(tuple(sorted((i, n)))
  46. for i, v in self.ngbh.items()
  47. for n in v)
  48. return [tuple(e) for e in edges]
  49. def remove_vop(self, a, avoid):
  50. """ Reduces VOP[a] to the identity """
  51. others = self.ngbh[a] - {avoid}
  52. swap_qubit = others.pop() if others else avoid
  53. for v in reversed(clifford.decompositions[self.vops[a]]):
  54. self.local_complementation(a if v == "x" else swap_qubit)
  55. def local_complementation(self, v):
  56. """ As defined in LISTING 1 of Anders & Briegel """
  57. for i, j in it.combinations(self.ngbh[v], 2):
  58. self.toggle_edge(i, j)
  59. # Update VOPs: TODO check ordering and replace by self.act_local_rotation
  60. self.vops[v] = clifford.times_table[
  61. self.vops[v]][clifford.by_name["sqx"]]
  62. for i in self.ngbh[v]:
  63. self.vops[i] = clifford.times_table[
  64. self.vops[i]][clifford.by_name["msqz"]]
  65. def act_local_rotation(self, a, op):
  66. """ Act a local rotation """
  67. self.vops[a] = clifford.times_table[op,self.vops[a]]
  68. def act_local_rotation_by_name(self, qubit, name):
  69. """ Shorthand """
  70. rotation = clifford.by_name[name]
  71. self.act_local_rotation(qubit, rotation)
  72. def act_hadamard(self, qubit):
  73. """ Shorthand """
  74. self.act_local_rotation(qubit, 10)
  75. def act_cz(self, a, b):
  76. """ Act a controlled-phase gate on two qubits """
  77. if self.ngbh[a] - {b}:
  78. self.remove_vop(a, b)
  79. if self.ngbh[b] - {a}:
  80. self.remove_vop(b, a)
  81. if self.ngbh[a] - {b}:
  82. self.remove_vop(a, b)
  83. edge = self.has_edge(a, b)
  84. new_edge, self.vops[a], self.vops[b] = clifford.cz_table[edge, self.vops[a], self.vops[b]]
  85. if new_edge != edge:
  86. self.toggle_edge(a, b)
  87. def measure_x(self, i):
  88. """ Measure the graph in the X-basis """
  89. #TODO
  90. pass
  91. def measure_y(self, i):
  92. """ Measure the graph in the Y-basis """
  93. #TODO
  94. pass
  95. def measure_Z(self, i):
  96. """ Measure the graph in the Z-basis """
  97. #TODO
  98. pass
  99. def order(self):
  100. """ Get the number of qubits """
  101. return len(self.vops)
  102. def __str__(self):
  103. """ Represent as a string for quick debugging """
  104. return "graph:\n vops: {}\n ngbh: {}\n"\
  105. .format(str(dict(self.vops)), str(dict(self.ngbh)))
  106. def to_json(self):
  107. """ Convert the graph to JSON form """
  108. #ngbh = {key: tuple(value) for key, value in self.ngbh.items()}
  109. meta = {key: value for key, value in self.meta.items()}
  110. edge = self.edgelist()
  111. return json.dumps({"vops": self.vops, "edge": edge, "meta": meta})
  112. def to_networkx(self):
  113. """ Convert the graph to a networkx graph """
  114. g = nx.Graph()
  115. g.edge = {node: {neighbour: {} for neighbour in neighbours}
  116. for node, neighbours in self.ngbh.items()}
  117. g.node = {node: {"vop": vop} for node, vop in self.vops.items()}
  118. for node, metadata in self.meta.items():
  119. g.node[node].update(metadata)
  120. return g
  121. def layout(self):
  122. """ Automatically lay out the graph """
  123. g = self.to_networkx()
  124. pos = nx.spring_layout(g, dim=3, scale=10)
  125. average = lambda axis: sum(p[axis] for p in pos.values())/float(len(pos))
  126. ax, ay, az = average(0), average(1), average(2)
  127. for key, (x, y, z) in pos.items():
  128. self.meta[key]["pos"] = {"x": round(x-ax, 0), "y": round(y-ay, 0), "z": round(z-az, 0)}
  129. def to_stabilizer(self):
  130. """ Get the stabilizer of this graph """
  131. # TODO: VOPs are not implemented yet
  132. output = ""
  133. for a in self.ngbh:
  134. for b in self.ngbh:
  135. if a == b:
  136. output += " X "
  137. elif a in self.ngbh[b]:
  138. output += " Z "
  139. else:
  140. output += " I "
  141. output += "\n"
  142. return output.strip()
  143. def adj_list(self):
  144. """ For comparison with Anders and Briegel's C++ implementation """
  145. rows = []
  146. for key, vop in self.vops.items():
  147. ngbh = " ".join(map(str, sorted(self.ngbh[key])))
  148. vop = clifford.ab_names.get(vop, vop)
  149. s = "Vertex {}: VOp {}, neighbors {}".format(key, vop, ngbh)
  150. rows.append(s)
  151. return "\n".join(rows)