Anders and Briegel in Python
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

308 lignes
10.0KB

  1. """
  2. Provides an extremely basic graph structure, based on key/value pairs
  3. """
  4. import itertools as it
  5. import json
  6. import qi, clifford, util
  7. import random
  8. class GraphState(object):
  9. def __init__(self, nodes=[]):
  10. self.adj, self.node = {}, {}
  11. self.add_nodes(nodes)
  12. def add_node(self, v, **kwargs):
  13. """ Add a node """
  14. assert not v in self.node
  15. self.adj[v] = {}
  16. self.node[v] = {"vop": clifford.by_name["hadamard"]}
  17. self.node[v].update(kwargs)
  18. def add_nodes(self, nodes):
  19. """ Add a buncha nodes """
  20. for n in nodes:
  21. self.add_node(n)
  22. def add_edge(self, v1, v2, data={}):
  23. """ Add an edge between two vertices in the self """
  24. assert v1 != v2
  25. self.adj[v1][v2] = data
  26. self.adj[v2][v1] = data
  27. def add_edges(self, edges):
  28. """ Add a buncha edges """
  29. for (v1, v2) in edges:
  30. self.add_edge(v1, v2)
  31. def del_edge(self, v1, v2):
  32. """ Delete an edge between two vertices in the self """
  33. del self.adj[v1][v2]
  34. del self.adj[v2][v1]
  35. def has_edge(self, v1, v2):
  36. """ Test existence of an edge between two vertices in the self """
  37. return v2 in self.adj[v1]
  38. def toggle_edge(self, v1, v2):
  39. """ Toggle an edge between two vertices in the self """
  40. if self.has_edge(v1, v2):
  41. self.del_edge(v1, v2)
  42. else:
  43. self.add_edge(v1, v2)
  44. def edgelist(self):
  45. """ Describe a graph as an edgelist """
  46. # TODO: inefficient
  47. edges = set(tuple(sorted((i, n)))
  48. for i, v in self.adj.items()
  49. for n in v)
  50. return tuple(edges)
  51. def remove_vop(self, a, avoid):
  52. """ Reduces VOP[a] to the identity """
  53. others = set(self.adj[a]) - {avoid}
  54. #TODO: this is a hack for determinsim. remove
  55. swap_qubit = min(others) if others else avoid
  56. #swap_qubit = others.pop() if others else avoid
  57. for v in reversed(clifford.decompositions[self.node[a]["vop"]]):
  58. if v == "x":
  59. self.local_complementation(a, "U ->")
  60. else:
  61. self.local_complementation(swap_qubit, "V ->")
  62. def local_complementation(self, v, prefix=""):
  63. """ As defined in LISTING 1 of Anders & Briegel """
  64. for i, j in it.combinations(self.adj[v], 2):
  65. self.toggle_edge(i, j)
  66. self.node[v]["vop"] = clifford.times_table[
  67. self.node[v]["vop"], clifford.by_name["msqx_h"]]
  68. for i in self.adj[v]:
  69. self.node[i]["vop"] = clifford.times_table[
  70. self.node[i]["vop"], clifford.by_name["sqz_h"]]
  71. def act_local_rotation(self, v, op):
  72. """ Act a local rotation """
  73. rotation = clifford.by_name[str(op)]
  74. self.node[v]["vop"] = clifford.times_table[
  75. rotation, self.node[v]["vop"]]
  76. def _update_vop(self, v, op):
  77. """ Update a VOP - only used internally"""
  78. rotation = clifford.by_name[str(op)]
  79. self.node[v]["vop"] = clifford.times_table[
  80. self.node[v]["vop"], rotation]
  81. def act_hadamard(self, qubit):
  82. """ Shorthand """
  83. self.act_local_rotation(qubit, 10)
  84. def _lonely(self, a, b):
  85. """ Is this qubit _lonely ? """
  86. return len(self.adj[a]) > (b in self.adj[a])
  87. def act_cz(self, a, b):
  88. """ Act a controlled-phase gate on two qubits """
  89. if self._lonely(a, b):
  90. self.remove_vop(a, b)
  91. if self._lonely(b, a):
  92. self.remove_vop(b, a)
  93. if self._lonely(a, b) and not clifford.is_diagonal(self.node[a]["vop"]):
  94. self.remove_vop(a, b)
  95. edge = self.has_edge(a, b)
  96. va = self.node[a]["vop"]
  97. vb = self.node[b]["vop"]
  98. new_edge, self.node[a]["vop"], self.node[b]["vop"] = \
  99. clifford.cz_table[int(edge), va, vb]
  100. if new_edge != edge:
  101. self.toggle_edge(a, b)
  102. def measure(self, node, basis, force=None):
  103. """ Measure in an arbitrary basis """
  104. basis = clifford.by_name[basis]
  105. ha = clifford.conjugation_table[self.node[node]["vop"]]
  106. basis, phase = clifford.conjugate(basis, ha)
  107. # Flip a coin
  108. result = force if force!=None else random.choice([0, 1])
  109. # Flip the result if we have negative phase
  110. if phase == -1:
  111. result = not result
  112. if basis == clifford.by_name["px"]:
  113. result = self._measure_x(node, result)
  114. elif basis == clifford.by_name["py"]:
  115. result = self._measure_y(node, result)
  116. elif basis == clifford.by_name["pz"]:
  117. result = self._measure_z(node, result)
  118. else:
  119. raise ValueError("You can only measure in {X,Y,Z}")
  120. # Flip the result if we have negative phase
  121. if phase == -1:
  122. result = not result
  123. return result
  124. def toggle_edges(self, a, b):
  125. """ Toggle edges between vertex sets a and b """
  126. # TODO: i'm pretty sure this is just a single-line it.combinations or equiv
  127. done = set()
  128. for i, j in it.product(a, b):
  129. if i != j and not (i, j) in done:
  130. done.add((i, j))
  131. done.add((j, i))
  132. self.toggle_edge(i, j)
  133. def _measure_x(self, node, result):
  134. """ Measure the graph in the X-basis """
  135. if len(self.adj[node]) == 0:
  136. return 0
  137. # Pick a vertex
  138. #friend = next(self.adj[node].iterkeys())
  139. # TODO this is enforced determinism for testing purposes
  140. friend = sorted(self.adj[node].keys())[0]
  141. # Update the VOPs. TODO: pretty ugly
  142. if result:
  143. # Do a z on all ngb(vb) \ ngb(v) \ {v}, and some other stuff
  144. self._update_vop(friend, "msqy")
  145. self._update_vop(node, "pz")
  146. for n in set(self.adj[friend]) - set(self.adj[node]) - {node}:
  147. self._update_vop(n, "pz")
  148. else:
  149. # Do a z on all ngb(v) \ ngb(vb) \ {vb}, and sqy on the friend
  150. self._update_vop(friend, "sqy")
  151. for n in set(self.adj[node]) - set(self.adj[friend]) - {friend}:
  152. self._update_vop(n, "pz")
  153. # Toggle the edges. TODO: Yuk. Just awful!
  154. a = set(self.adj[node].keys())
  155. b = set(self.adj[friend].keys())
  156. self.toggle_edges(a, b)
  157. intersection = a & b
  158. for i, j in it.combinations(intersection, 2):
  159. self.toggle_edge(i, j)
  160. for n in a - {friend}:
  161. self.toggle_edge(friend, n)
  162. return result
  163. def _measure_y(self, node, result):
  164. """ Measure the graph in the Y-basis """
  165. # Do some rotations
  166. for neighbour in self.adj[node]:
  167. self._update_vop(neighbour, "sqz" if result else "msqz")
  168. # A sort of local complementation
  169. vngbh = set(self.adj[node]) | {node}
  170. for i, j in it.combinations(vngbh, 2):
  171. self.toggle_edge(i, j)
  172. self._update_vop(node, 5 if result else 6) # TODO: naming: # lcoS.herm_adjoint() if result else lcoS
  173. return result
  174. def _measure_z(self, node, result):
  175. """ Measure the graph in the Z-basis """
  176. # Disconnect
  177. for neighbour in tuple(self.adj[node]):
  178. self.del_edge(node, neighbour)
  179. if result:
  180. self._update_vop(neighbour, "pz")
  181. # Rotate
  182. if result:
  183. self._update_vop(node, "px")
  184. self._update_vop(node, "hadamard")
  185. else:
  186. self._update_vop(node, "hadamard")
  187. return result
  188. def order(self):
  189. """ Get the number of qubits """
  190. return len(self.node)
  191. def __str__(self):
  192. """ Represent as a string for quick debugging """
  193. s = ""
  194. for key in sorted(self.node.keys()):
  195. s += "{}: {}\t".format(key, clifford.get_name(self.node[key]["vop"]).replace("YC", "-"))
  196. if self.adj[key]:
  197. s += str(tuple(self.adj[key].keys())).replace(" ", "")
  198. else:
  199. s += "-"
  200. s += "\n"
  201. return s
  202. def to_json(self, stringify=False):
  203. """
  204. Convert the graph to JSON form.
  205. JSON keys must be strings, But sometimes it is useful to have
  206. a JSON-like object whose keys are tuples!
  207. """
  208. if stringify:
  209. node = {str(key): value for key, value in self.node.items()}
  210. adj = {str(key): {str(key): value for key, value in ngbh.items()}
  211. for key, ngbh in self.adj.items()}
  212. return {"node": node, "adj": adj}
  213. else:
  214. return {"node": self.node, "adj": self.adj}
  215. def from_json(self, data):
  216. """ Reconstruct from JSON """
  217. self.__init__([])
  218. # TODO
  219. def to_state_vector(self):
  220. """ Get the full state vector """
  221. if len(self.node) > 15:
  222. raise ValueError("Cannot build state vector: too many qubits")
  223. state = qi.CircuitModel(len(self.node))
  224. for i in range(len(self.node)):
  225. state.act_hadamard(i)
  226. for i, j in self.edgelist():
  227. state.act_cz(i, j)
  228. for i, n in self.node.items():
  229. state.act_local_rotation(i, clifford.unitaries[n["vop"]])
  230. return state
  231. def to_stabilizer(self):
  232. """ Get the stabilizer of this graph """
  233. return
  234. output = {a: {} for a in self.node}
  235. for a, b in it.product(self.node, self.node):
  236. if a == b:
  237. output[a][b] = "X"
  238. elif a in self.adj[b]:
  239. output[a][b] = "Z"
  240. else:
  241. output[a][b] = "I"
  242. # TODO: signs
  243. return output
  244. def __eq__(self, other):
  245. """ Check equality between graphs """
  246. if str(type(other)) == "<class 'anders_briegel.graphsim.GraphRegister'>":
  247. return self.to_json() == other.to_json()
  248. return self.adj == other.adj and self.node == other.node
  249. if __name__ == '__main__':
  250. g = GraphState()
  251. g.add_nodes(range(10))
  252. g.add_edge(0, 5)
  253. g.act_local_rotation(6, 10)
  254. print g
  255. print g.to_state_vector()