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.

378 lines
13KB

  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, node, **kwargs):
  21. """ Add a node.
  22. :param node: The name of the node, e.g. ``9``, ``start``
  23. :type node: Any hashable type
  24. :param kwargs: Any extra node attributes
  25. Example of using node attributes ::
  26. >>> g.add_node(0, label="fred", position=(1,2,3))
  27. >>> g.node[0]["label"]
  28. fred
  29. """
  30. assert not node in self.node, "Node {} already exists".format(v)
  31. self.adj[node] = {}
  32. self.node[node] = {"vop": clifford.by_name["hadamard"]}
  33. self.node[node].update(kwargs)
  34. def add_nodes(self, nodes):
  35. """ Add many nodes in one shot. """
  36. for n in nodes:
  37. self.add_node(n)
  38. def act_circuit(self, circuit):
  39. """ Run many gates in one call.
  40. :param circuit: An iterable containing tuples of the form ``(node, operation)``. If ``operation`` is a name for a local operation (e.g. ``6``, ``hadamard``) then that operation is performed on ``node``. If ``operation`` is ``cz`` then a CZ is performed on the two nodes in ``node``.
  41. Example (makes a Bell pair)::
  42. >>> g.act_circuit([(0, "hadamard"), (1, "hadamard"), ((0, 1), "cz")])
  43. """
  44. for node, operation in circuit:
  45. if operation == "cz":
  46. self.act_cz(*node)
  47. else:
  48. self.act_local_rotation(node, operation)
  49. def _add_edge(self, v1, v2, data={}):
  50. """ Add an edge between two vertices """
  51. self.adj[v1][v2] = data
  52. self.adj[v2][v1] = data
  53. def _del_edge(self, v1, v2):
  54. """ Delete an edge between two vertices """
  55. del self.adj[v1][v2]
  56. del self.adj[v2][v1]
  57. def has_edge(self, v1, v2):
  58. """ Test existence of an edge between two vertices """
  59. return v2 in self.adj[v1]
  60. def _toggle_edge(self, v1, v2):
  61. """ Toggle an edge between two vertices """
  62. if self.has_edge(v1, v2):
  63. self._del_edge(v1, v2)
  64. else:
  65. self._add_edge(v1, v2)
  66. def edgelist(self):
  67. """ Describe a graph as an edgelist # TODO: inefficient """
  68. edges = set(tuple(sorted((i, n)))
  69. for i, v in self.adj.items()
  70. for n in v)
  71. return tuple(edges)
  72. def remove_vop(self, a, avoid):
  73. """ Reduces VOP[a] to the identity """
  74. others = set(self.adj[a]) - {avoid}
  75. if self.deterministic:
  76. swap_qubit = min(others) if others else avoid
  77. else:
  78. swap_qubit = others.pop() if others else avoid
  79. for v in reversed(clifford.decompositions[self.node[a]["vop"]]):
  80. if v == "x":
  81. self.local_complementation(a, "U ->")
  82. else:
  83. self.local_complementation(swap_qubit, "V ->")
  84. def local_complementation(self, v, prefix=""):
  85. """ As defined in LISTING 1 of Anders & Briegel """
  86. for i, j in it.combinations(self.adj[v], 2):
  87. self._toggle_edge(i, j)
  88. self.node[v]["vop"] = clifford.times_table[
  89. self.node[v]["vop"], clifford.by_name["msqx_h"]]
  90. for i in self.adj[v]:
  91. self.node[i]["vop"] = clifford.times_table[
  92. self.node[i]["vop"], clifford.by_name["sqz_h"]]
  93. def act_local_rotation(self, node, operation):
  94. """ Act a local rotation on a qubit
  95. :param node: The index of the node to act on
  96. :param operation: The Clifford-group operation to perform.
  97. """
  98. rotation = clifford.by_name[str(operation)]
  99. self.node[node]["vop"] = clifford.times_table[
  100. rotation, self.node[node]["vop"]]
  101. def _update_vop(self, v, op):
  102. """ Update a VOP - only used internally"""
  103. rotation = clifford.by_name[str(op)]
  104. self.node[v]["vop"] = clifford.times_table[
  105. self.node[v]["vop"], rotation]
  106. def act_hadamard(self, qubit):
  107. """ Shorthand for ``self.act_local_rotation(qubit, "hadamard")`` """
  108. self.act_local_rotation(qubit, 10)
  109. def _lonely(self, a, b):
  110. """ Is this qubit _lonely ? """
  111. return len(self.adj[a]) > (b in self.adj[a])
  112. def act_cz(self, a, b):
  113. """ Act a controlled-phase gate on two qubits
  114. :param a: The first qubit
  115. :param b: The second qubit
  116. """
  117. if self._lonely(a, b):
  118. self.remove_vop(a, b)
  119. if self._lonely(b, a):
  120. self.remove_vop(b, a)
  121. if self._lonely(a, b) and not clifford.is_diagonal(self.node[a]["vop"]):
  122. self.remove_vop(a, b)
  123. edge = self.has_edge(a, b)
  124. va = self.node[a]["vop"]
  125. vb = self.node[b]["vop"]
  126. new_edge, self.node[a]["vop"], self.node[b]["vop"] = \
  127. clifford.cz_table[int(edge), va, vb]
  128. if new_edge != edge:
  129. self._toggle_edge(a, b)
  130. def measure(self, node, basis, force=None):
  131. """ Measure in an arbitrary basis
  132. :param node: The name of the qubit to measure.
  133. :param basis: The basis in which to measure.
  134. :type basis: :math:`\in` ``{"px", "py", "pz"}``
  135. :param force: Measurements in quantum mechanics are probabilistic. If you want to force a particular outcome, use the ``force``.
  136. :type force: boolean
  137. """
  138. basis = clifford.by_name[basis]
  139. ha = clifford.conjugation_table[self.node[node]["vop"]]
  140. basis, phase = clifford.conjugate(basis, ha)
  141. # Flip a coin
  142. result = force if force != None else random.choice([0, 1])
  143. # Flip the result if we have negative phase
  144. if phase == -1:
  145. result = not result
  146. if basis == clifford.by_name["px"]:
  147. result = self._measure_x(node, result)
  148. elif basis == clifford.by_name["py"]:
  149. result = self._measure_y(node, result)
  150. elif basis == clifford.by_name["pz"]:
  151. result = self._measure_z(node, result)
  152. else:
  153. raise ValueError("You can only measure in {X,Y,Z}")
  154. # Flip the result if we have negative phase
  155. if phase == -1:
  156. result = not result
  157. return result
  158. def _toggle_edges(self, a, b):
  159. """ Toggle edges between vertex sets a and b """
  160. # TODO: i'm pretty sure this is just a single-line it.combinations or
  161. # equiv
  162. done = set()
  163. for i, j in it.product(a, b):
  164. if i != j and not (i, j) in done:
  165. done.add((i, j))
  166. done.add((j, i))
  167. self._toggle_edge(i, j)
  168. def _measure_x(self, node, result):
  169. """ Measure the graph in the X-basis """
  170. if len(self.adj[node]) == 0:
  171. return 0
  172. # Pick a vertex
  173. if self.deterministic:
  174. friend = sorted(self.adj[node].keys())[0]
  175. else:
  176. friend = next(self.adj[node].iterkeys())
  177. # Update the VOPs. TODO: pretty ugly
  178. if result:
  179. # Do a z on all ngb(vb) \ ngb(v) \ {v}, and some other stuff
  180. self._update_vop(friend, "msqy")
  181. self._update_vop(node, "pz")
  182. for n in set(self.adj[friend]) - set(self.adj[node]) - {node}:
  183. self._update_vop(n, "pz")
  184. else:
  185. # Do a z on all ngb(v) \ ngb(vb) \ {vb}, and sqy on the friend
  186. self._update_vop(friend, "sqy")
  187. for n in set(self.adj[node]) - set(self.adj[friend]) - {friend}:
  188. self._update_vop(n, "pz")
  189. # Toggle the edges. TODO: Yuk. Just awful!
  190. a = set(self.adj[node].keys())
  191. b = set(self.adj[friend].keys())
  192. self._toggle_edges(a, b)
  193. intersection = a & b
  194. for i, j in it.combinations(intersection, 2):
  195. self._toggle_edge(i, j)
  196. for n in a - {friend}:
  197. self._toggle_edge(friend, n)
  198. return result
  199. def _measure_y(self, node, result):
  200. """ Measure the graph in the Y-basis """
  201. # Do some rotations
  202. for neighbour in self.adj[node]:
  203. self._update_vop(neighbour, "sqz" if result else "msqz")
  204. # A sort of local complementation
  205. vngbh = set(self.adj[node]) | {node}
  206. for i, j in it.combinations(vngbh, 2):
  207. self._toggle_edge(i, j)
  208. self._update_vop(node, 5 if result else 6)
  209. # TODO: naming: # lcoS.herm_adjoint() if result else
  210. # lcoS
  211. return result
  212. def _measure_z(self, node, result):
  213. """ Measure the graph in the Z-basis """
  214. # Disconnect
  215. for neighbour in tuple(self.adj[node]):
  216. self._del_edge(node, neighbour)
  217. if result:
  218. self._update_vop(neighbour, "pz")
  219. # Rotate
  220. if result:
  221. self._update_vop(node, "px")
  222. self._update_vop(node, "hadamard")
  223. else:
  224. self._update_vop(node, "hadamard")
  225. return result
  226. def order(self):
  227. """ Get the number of qubits """
  228. return len(self.node)
  229. def __str__(self):
  230. """ Represent as a string for quick debugging """
  231. s = ""
  232. for key in sorted(self.node.keys()):
  233. s += "{}: {}\t".format(
  234. key, clifford.get_name(self.node[key]["vop"]).replace("YC", "-"))
  235. if self.adj[key]:
  236. s += str(tuple(self.adj[key].keys())).replace(" ", "")
  237. else:
  238. s += "-"
  239. s += "\n"
  240. return s
  241. def to_json(self, stringify=False):
  242. """ Convert the graph to JSON-like form.
  243. :param stringify: JSON keys must be strings, But sometimes it is useful to have a JSON-like object whose keys are tuples.
  244. If you want to dump a graph do disk, do something like this::
  245. >>> import json
  246. >>> with open("graph.json") as f:
  247. json.dump(graph.to_json(True), f)
  248. """
  249. if stringify:
  250. node = {str(key): value for key, value in self.node.items()}
  251. adj = {str(key): {str(key): value for key, value in ngbh.items()}
  252. for key, ngbh in self.adj.items()}
  253. return {"node": node, "adj": adj}
  254. else:
  255. return {"node": self.node, "adj": self.adj}
  256. def from_json(self, data):
  257. """ Reconstruct from JSON """
  258. self.__init__([])
  259. # TODO
  260. def to_state_vector(self):
  261. """ Get the full state vector corresponding to this stabilizer state. Useful for debugging, interface with other simulators.
  262. The output state is represented as a ``abp.qi.CircuitModel``::
  263. >>> print g.to_state_vector()
  264. |00000>: 0.18+0.00j
  265. |00001>: 0.18+0.00j ...
  266. .. warning::
  267. Obviously this method becomes very slow for more than about ten qubits!
  268. """
  269. if len(self.node) > 15:
  270. raise ValueError("Cannot build state vector: too many qubits")
  271. state = qi.CircuitModel(len(self.node))
  272. for i in range(len(self.node)):
  273. state.act_hadamard(i)
  274. for i, j in self.edgelist():
  275. state.act_cz(i, j)
  276. for i, n in self.node.items():
  277. state.act_local_rotation(i, clifford.unitaries[n["vop"]])
  278. return state
  279. def to_stabilizer(self):
  280. """ Get the stabilizer tableau. Work in progress!
  281. """
  282. return
  283. output = {a: {} for a in self.node}
  284. for a, b in it.product(self.node, self.node):
  285. if a == b:
  286. output[a][b] = "X"
  287. elif a in self.adj[b]:
  288. output[a][b] = "Z"
  289. else:
  290. output[a][b] = "I"
  291. # TODO: signs
  292. return output
  293. def __eq__(self, other):
  294. """ Check equality between GraphStates """
  295. return self.adj == other.adj and self.node == other.node
  296. if __name__ == '__main__':
  297. g = GraphState()
  298. g.add_nodes(range(10))
  299. g._add_edge(0, 5)
  300. g.act_local_rotation(6, 10)
  301. print g
  302. print g.to_state_vector()