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.

222 lines
7.1KB

  1. """
  2. Provides an extremely basic graph structure, based on neighbour lists
  3. """
  4. import itertools as it
  5. import clifford
  6. import json
  7. import qi
  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, nodes = []):
  14. self.ngbh = {}
  15. self.vops = {}
  16. self.meta = {}
  17. self.add_nodes(nodes)
  18. def add_node(self, v):
  19. """ Add a node """
  20. self.ngbh[v] = set()
  21. self.vops[v] = clifford.by_name["hadamard"]
  22. self.meta[v] = dict()
  23. def add_nodes(self, nodes):
  24. """ Add a buncha nodes """
  25. for n in nodes:
  26. self.add_node(n)
  27. def add_edge(self, v1, v2):
  28. """ Add an edge between two vertices in the self """
  29. assert v1 != v2
  30. self.ngbh[v1].add(v2)
  31. self.ngbh[v2].add(v1)
  32. def add_edges(self, edges):
  33. """ Add a buncha edges """
  34. for (v1, v2) in edges:
  35. self.add_edge(v1, v2)
  36. def del_edge(self, v1, v2):
  37. """ Delete an edge between two vertices in the self """
  38. self.ngbh[v1].remove(v2)
  39. self.ngbh[v2].remove(v1)
  40. def has_edge(self, v1, v2):
  41. """ Test existence of an edge between two vertices in the self """
  42. return v2 in self.ngbh[v1]
  43. def toggle_edge(self, v1, v2):
  44. """ Toggle an edge between two vertices in the self """
  45. if self.has_edge(v1, v2):
  46. self.del_edge(v1, v2)
  47. else:
  48. self.add_edge(v1, v2)
  49. def edgelist(self):
  50. """ Describe a graph as an edgelist """
  51. edges = frozenset(tuple(sorted((i, n)))
  52. for i, v in self.ngbh.items()
  53. for n in v)
  54. return [tuple(e) for e in edges]
  55. def remove_vop(self, a, avoid):
  56. """ Reduces VOP[a] to the identity """
  57. others = self.ngbh[a] - {avoid}
  58. swap_qubit = others.pop() if others else avoid
  59. for v in reversed(clifford.decompositions[self.vops[a]]):
  60. self.local_complementation(a if v == "x" else swap_qubit)
  61. def local_complementation(self, v):
  62. """ As defined in LISTING 1 of Anders & Briegel """
  63. for i, j in it.combinations(self.ngbh[v], 2):
  64. self.toggle_edge(i, j)
  65. # Update VOPs: TODO check ordering and replace by
  66. # self.act_local_rotation
  67. self.vops[v] = clifford.times_table[
  68. self.vops[v]][clifford.by_name["sqx"]]
  69. for i in self.ngbh[v]:
  70. self.vops[i] = clifford.times_table[
  71. self.vops[i]][clifford.by_name["msqz"]]
  72. def act_local_rotation(self, a, op):
  73. """ Act a local rotation """
  74. self.vops[a] = clifford.times_table[op, self.vops[a]]
  75. def act_local_rotation_by_name(self, qubit, name):
  76. """ Shorthand """
  77. rotation = clifford.by_name[name]
  78. self.act_local_rotation(qubit, rotation)
  79. def act_hadamard(self, qubit):
  80. """ Shorthand """
  81. self.act_local_rotation(qubit, 10)
  82. def act_cz(self, a, b):
  83. """ Act a controlled-phase gate on two qubits """
  84. if self.ngbh[a] - {b}:
  85. self.remove_vop(a, b)
  86. if self.ngbh[b] - {a}:
  87. self.remove_vop(b, a)
  88. if self.ngbh[a] - {b}:
  89. self.remove_vop(a, b)
  90. edge = self.has_edge(a, b)
  91. new_edge, self.vops[a], self.vops[
  92. b] = clifford.cz_table[edge, self.vops[a], self.vops[b]]
  93. if new_edge != edge:
  94. self.toggle_edge(a, b)
  95. def measure_z(self, node, force=None):
  96. """ Measure the graph in the Z-basis """
  97. res = force if force else np.random.choice([0, 1])
  98. # Disconnect
  99. for neighbour in self.ngbh[node]:
  100. self.del_edge(node, neighbour)
  101. if res:
  102. self.act_local_rotation_by_name(neighbour, "pz")
  103. # Set final state as appropriate
  104. if res:
  105. self.act_local_rotation_by_name(node, "px")
  106. self.act_local_rotation_by_name(node, "hadamard")
  107. else:
  108. self.act_local_rotation_by_name(node, "hadamard")
  109. return res
  110. def measure_x(self, i):
  111. """ Measure the graph in the X-basis """
  112. # TODO
  113. pass
  114. def measure_y(self, i):
  115. """ Measure the graph in the Y-basis """
  116. # TODO
  117. pass
  118. def order(self):
  119. """ Get the number of qubits """
  120. return len(self.vops)
  121. def __str__(self):
  122. """ Represent as a string for quick debugging """
  123. vopstr = {key: clifford.get_name(value)
  124. for key, value in self.vops.items()}
  125. nbstr = str(self.ngbh)
  126. return "graph:\n vops: {}\n ngbh: {}\n".format(vopstr, nbstr)
  127. def to_json(self):
  128. """ Convert the graph to JSON form """
  129. meta = {key: value for key, value in self.meta.items()}
  130. edge = self.edgelist()
  131. return json.dumps({"nodes": self.vops, "edges": edge, "meta": meta})
  132. def to_networkx(self):
  133. """ Convert the graph to a networkx graph """
  134. g = nx.Graph()
  135. g.edge = {node: {neighbour: {} for neighbour in neighbours}
  136. for node, neighbours in self.ngbh.items()}
  137. g.node = {node: {"vop": vop} for node, vop in self.vops.items()}
  138. for node, metadata in self.meta.items():
  139. g.node[node].update(metadata)
  140. return g
  141. def to_state_vector(self):
  142. """ Get the full state vector """
  143. if len(self.vops) > 15:
  144. raise ValueError("Cannot build state vector: too many qubits")
  145. state = qi.CircuitModel(len(self.vops))
  146. for i in range(len(self.vops)):
  147. state.act_hadamard(i)
  148. for i, j in self.edgelist():
  149. state.act_cz(i, j)
  150. for i, u in self.vops.items():
  151. state.act_local_rotation(i, clifford.unitaries[u])
  152. return state
  153. def layout(self):
  154. """ Automatically lay out the graph """
  155. g = self.to_networkx()
  156. pos = nx.spring_layout(g, dim=3, scale=10)
  157. average = lambda axis: sum(p[axis]
  158. for p in pos.values()) / float(len(pos))
  159. ax, ay, az = average(0), average(1), average(2)
  160. for key, (x, y, z) in pos.items():
  161. self.meta[key]["pos"] = {
  162. "x": round(x - ax, 0),
  163. "y": round(y - ay, 0),
  164. "z": round(z - az, 0)}
  165. def to_stabilizer(self):
  166. """ Get the stabilizer of this graph """
  167. # TODO: VOPs are not implemented yet
  168. output = ""
  169. for a in self.ngbh:
  170. for b in self.ngbh:
  171. if a == b:
  172. output += " X "
  173. elif a in self.ngbh[b]:
  174. output += " Z "
  175. else:
  176. output += " I "
  177. output += "\n"
  178. return output
  179. def adj_list(self):
  180. """ For comparison with Anders and Briegel's C++ implementation """
  181. rows = []
  182. for key, vop in self.vops.items():
  183. ngbh = " ".join(map(str, sorted(self.ngbh[key])))
  184. vop = clifford.get_name(vop)
  185. s = "Vertex {}: VOp {}, neighbors {}".format(key, vop, ngbh)
  186. rows.append(s)
  187. return " \n".join(rows) + " \n"