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.

278 lignes
9.1KB

  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 # TODO: maybe this is the only problematic part
  57. print "SWAPPING WITH {} (options were {})".format(swap_qubit, tuple(others))
  58. for v in reversed(clifford.decompositions[self.node[a]["vop"]]):
  59. if v == "x":
  60. self.local_complementation(a, "U ->")
  61. else:
  62. self.local_complementation(swap_qubit, "V ->")
  63. def local_complementation(self, v, prefix=""):
  64. """ As defined in LISTING 1 of Anders & Briegel """
  65. for i, j in it.combinations(self.adj[v], 2):
  66. self.toggle_edge(i, j)
  67. self.node[v]["vop"] = clifford.times_table[
  68. self.node[v]["vop"], clifford.by_name["msqx_h"]]
  69. for i in self.adj[v]:
  70. self.node[i]["vop"] = clifford.times_table[
  71. self.node[i]["vop"], clifford.by_name["sqz_h"]]
  72. def act_local_rotation(self, v, op):
  73. """ Act a local rotation """
  74. rotation = clifford.by_name[str(op)]
  75. self.node[v]["vop"] = clifford.times_table[
  76. rotation, self.node[v]["vop"]]
  77. def act_hadamard(self, qubit):
  78. """ Shorthand """
  79. self.act_local_rotation(qubit, 10)
  80. def lonely(self, a, b):
  81. """ Is this qubit lonely ? """
  82. return len(self.adj[a]) > (b in self.adj[a])
  83. def act_cz(self, a, b):
  84. """ Act a controlled-phase gate on two qubits """
  85. if self.lonely(a, b):
  86. self.remove_vop(a, b)
  87. if self.lonely(b, a):
  88. self.remove_vop(b, a)
  89. if self.lonely(a, b) and not clifford.is_diagonal(self.node[a]["vop"]):
  90. self.remove_vop(a, b)
  91. edge = self.has_edge(a, b)
  92. va = self.node[a]["vop"]
  93. vb = self.node[b]["vop"]
  94. new_edge, self.node[a]["vop"], self.node[b]["vop"] = \
  95. clifford.cz_table[edge, va, vb]
  96. if new_edge != edge:
  97. self.toggle_edge(a, b)
  98. def measure(self, node, basis, force=None):
  99. """ Measure in an arbitrary basis """
  100. basis = clifford.by_name[basis]
  101. ha = clifford.conjugation_table[self.node[node]["vop"]]
  102. basis, phase = clifford.conjugate(basis, ha)
  103. # Flip a coin
  104. result = force if force!=None else random.choice([0, 1])
  105. if basis == clifford.by_name["px"]:
  106. result = self.measure_x(node, result)
  107. elif basis == clifford.by_name["py"]:
  108. result = self.measure_y(node, result)
  109. elif basis == clifford.by_name["pz"]:
  110. result = self.measure_z(node, result)
  111. else:
  112. raise ValueError("You can only measure in {X,Y,Z}")
  113. # Flip the result if we have negative phase
  114. if phase == -1:
  115. result = not result
  116. return result
  117. def toggle_edges(a, b):
  118. """ Toggle edges between vertex sets a and b """
  119. done = {}
  120. for i, j in it.product(a, b):
  121. if i == j and not (i, j) in done:
  122. done.add((i, j), (j, i))
  123. self.toggle_edge(i, j)
  124. def measure_x(self, node, result):
  125. """ Measure the graph in the X-basis """
  126. if len(self.adj[node]) == 0:
  127. return 0
  128. # Pick a vertex
  129. friend = next(self.adj[node].iterkeys())
  130. # TODO: yuk yuk yuk
  131. if result:
  132. # Do a z on all ngb(vb) \ ngb(v) \ {v}, and some other stuff
  133. self.act_local_rotation(node, "pz")
  134. self.act_local_rotation(friend, "msqy")
  135. for n in set(self.adj[friend]) - set(self.adj(node)) - {node}:
  136. self.act_local_rotation(n, "pz")
  137. else:
  138. # Do a z on all ngb(v) \ ngb(vb) \ {vb}, and sqy on the friend
  139. self.act_local_rotation(friend, "sqy")
  140. for n in set(self.adj[node]) - set(self.adj(friend)) - {friend}:
  141. self.act_local_rotation(n, "pz")
  142. # TODO: Yuk. Just awful!
  143. a = set(self.adj[node].keys())
  144. b = set(self.adj[friend].keys())
  145. self.toggle_edges(a, b)
  146. intersection = a & b
  147. for i, j in it.combinations(intersection, 2):
  148. self.toggle_edge(i, j)
  149. for n in a - {friend}:
  150. self.toggle_edge(friend, n)
  151. return result
  152. def measure_y(self, node, result):
  153. """ Measure the graph in the Y-basis """
  154. # Do some rotations
  155. for neighbour in self.adj[node]:
  156. # NB: should these be hermitian_conjugated?
  157. self.act_local_rotation(neighbour, "sqz" if result else "msqz")
  158. # A sort of local complementation
  159. vngbh = set(self.adj[node]) | {node}
  160. for i, j in it.combinations(vngbh, 2):
  161. self.toggle_edge(i, j)
  162. self.act_local_rotation(node, "msqz" if result else "msqz_h")
  163. return result
  164. def measure_z(self, node, result):
  165. """ Measure the graph in the Z-basis """
  166. # Disconnect
  167. for neighbour in self.adj[node]:
  168. self.del_edge(node, neighbour)
  169. if result:
  170. self.act_local_rotation(neighbour, "pz")
  171. # Rotate
  172. self.act_local_rotation(node, "hadamard")
  173. if result:
  174. self.act_local_rotation(node, "px")
  175. return result
  176. def order(self):
  177. """ Get the number of qubits """
  178. return len(self.node)
  179. def __str__(self):
  180. """ Represent as a string for quick debugging """
  181. node = {key: clifford.get_name(value["vop"])
  182. for key, value in self.node.items()}
  183. nbstr = str(self.adj)
  184. return "graph:\n node: {}\n adj: {}\n".format(node, nbstr)
  185. def to_json(self, stringify=False):
  186. """
  187. Convert the graph to JSON form.
  188. JSON keys must be strings, But sometimes it is useful to have
  189. a JSON-like object whose keys are tuples!
  190. """
  191. if stringify:
  192. node = {str(key): value for key, value in self.node.items()}
  193. adj = {str(key): {str(key): value for key, value in ngbh.items()}
  194. for key, ngbh in self.adj.items()}
  195. return {"node": node, "adj": adj}
  196. else:
  197. return {"node": self.node, "adj": self.adj}
  198. def from_json(self, data):
  199. """ Reconstruct from JSON """
  200. self.__init__([])
  201. # TODO
  202. def to_state_vector(self):
  203. """ Get the full state vector """
  204. if len(self.node) > 15:
  205. raise ValueError("Cannot build state vector: too many qubits")
  206. state = qi.CircuitModel(len(self.node))
  207. for i in range(len(self.node)):
  208. state.act_hadamard(i)
  209. for i, j in self.edgelist():
  210. state.act_cz(i, j)
  211. for i, n in self.node.items():
  212. state.act_local_rotation(i, clifford.unitaries[n["vop"]])
  213. return state
  214. def to_stabilizer(self):
  215. """ Get the stabilizer of this graph """
  216. return
  217. output = {a: {} for a in self.node}
  218. for a, b in it.product(self.node, self.node):
  219. if a == b:
  220. output[a][b] = "X"
  221. elif a in self.adj[b]:
  222. output[a][b] = "Z"
  223. else:
  224. output[a][b] = "I"
  225. # TODO: signs
  226. return output
  227. def __eq__(self, other):
  228. """ Check equality between graphs """
  229. return self.adj == other.adj and self.node == other.node