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.

239 lines
7.7KB

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