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.

220 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. msqx_h = clifford.conjugation_table[clifford.by_name["msqx"]]
  66. sqz_h = clifford.conjugation_table[clifford.by_name["sqz"]]
  67. self.vops[v] = clifford.times_table[self.vops[v], msqx_h]
  68. for i in self.ngbh[v]:
  69. self.vops[i] = clifford.times_table[self.vops[i], sqz_h]
  70. def act_local_rotation(self, a, op):
  71. """ Act a local rotation """
  72. self.vops[a] = clifford.times_table[op, self.vops[a]]
  73. def act_local_rotation_by_name(self, qubit, name):
  74. """ Shorthand """
  75. rotation = clifford.by_name[name]
  76. self.act_local_rotation(qubit, rotation)
  77. def act_hadamard(self, qubit):
  78. """ Shorthand """
  79. self.act_local_rotation(qubit, 10)
  80. def act_cz(self, a, b):
  81. """ Act a controlled-phase gate on two qubits """
  82. if self.ngbh[a] - {b}:
  83. self.remove_vop(a, b)
  84. if self.ngbh[b] - {a}:
  85. self.remove_vop(b, a)
  86. if self.ngbh[a] - {b}:
  87. self.remove_vop(a, b)
  88. edge = self.has_edge(a, b)
  89. new_edge, self.vops[a], self.vops[
  90. b] = clifford.cz_table[edge, self.vops[a], self.vops[b]]
  91. if new_edge != edge:
  92. self.toggle_edge(a, b)
  93. def measure_z(self, node, force=None):
  94. """ Measure the graph in the Z-basis """
  95. res = force if force else np.random.choice([0, 1])
  96. # Disconnect
  97. for neighbour in self.ngbh[node]:
  98. self.del_edge(node, neighbour)
  99. if res:
  100. self.act_local_rotation_by_name(neighbour, "pz")
  101. # Set final state as appropriate
  102. if res:
  103. self.act_local_rotation_by_name(node, "px")
  104. self.act_local_rotation_by_name(node, "hadamard")
  105. else:
  106. self.act_local_rotation_by_name(node, "hadamard")
  107. return res
  108. def measure_x(self, i):
  109. """ Measure the graph in the X-basis """
  110. # TODO
  111. pass
  112. def measure_y(self, i):
  113. """ Measure the graph in the Y-basis """
  114. # TODO
  115. pass
  116. def order(self):
  117. """ Get the number of qubits """
  118. return len(self.vops)
  119. def __str__(self):
  120. """ Represent as a string for quick debugging """
  121. vopstr = {key: clifford.get_name(value)
  122. for key, value in self.vops.items()}
  123. nbstr = str(self.ngbh)
  124. return "graph:\n vops: {}\n ngbh: {}\n".format(vopstr, nbstr)
  125. def to_json(self):
  126. """ Convert the graph to JSON form """
  127. meta = {key: value for key, value in self.meta.items()}
  128. edge = self.edgelist()
  129. return json.dumps({"nodes": self.vops, "edges": edge, "meta": meta})
  130. def to_networkx(self):
  131. """ Convert the graph to a networkx graph """
  132. g = nx.Graph()
  133. g.edge = {node: {neighbour: {} for neighbour in neighbours}
  134. for node, neighbours in self.ngbh.items()}
  135. g.node = {node: {"vop": vop} for node, vop in self.vops.items()}
  136. for node, metadata in self.meta.items():
  137. g.node[node].update(metadata)
  138. return g
  139. def to_state_vector(self):
  140. """ Get the full state vector """
  141. if len(self.vops) > 15:
  142. raise ValueError("Cannot build state vector: too many qubits")
  143. state = qi.CircuitModel(len(self.vops))
  144. for i in range(len(self.vops)):
  145. state.act_hadamard(i)
  146. for i, j in self.edgelist():
  147. state.act_cz(i, j)
  148. for i, u in self.vops.items():
  149. state.act_local_rotation(i, clifford.unitaries[u])
  150. return state
  151. def layout(self):
  152. """ Automatically lay out the graph """
  153. g = self.to_networkx()
  154. pos = nx.spring_layout(g, dim=3, scale=10)
  155. average = lambda axis: sum(p[axis]
  156. for p in pos.values()) / float(len(pos))
  157. ax, ay, az = average(0), average(1), average(2)
  158. for key, (x, y, z) in pos.items():
  159. self.meta[key]["pos"] = {
  160. "x": round(x - ax, 0),
  161. "y": round(y - ay, 0),
  162. "z": round(z - az, 0)}
  163. def to_stabilizer(self):
  164. """ Get the stabilizer of this graph """
  165. # TODO: VOPs are not implemented yet
  166. output = ""
  167. for a in self.ngbh:
  168. for b in self.ngbh:
  169. if a == b:
  170. output += " X "
  171. elif a in self.ngbh[b]:
  172. output += " Z "
  173. else:
  174. output += " I "
  175. output += "\n"
  176. return output
  177. def adj_list(self):
  178. """ For comparison with Anders and Briegel's C++ implementation """
  179. rows = []
  180. for key, vop in self.vops.items():
  181. ngbh = " ".join(map(str, sorted(self.ngbh[key])))
  182. vop = clifford.get_name(vop)
  183. s = "Vertex {}: VOp {}, neighbors {}".format(key, vop, ngbh)
  184. rows.append(s)
  185. return " \n".join(rows) + " \n"