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.

234 lines
7.5KB

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