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.

323 lines
11KB

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