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.

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