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.

423 lines
15KB

  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, node, avoid):
  73. """ Attempts to remove the vertex operator on a particular qubit.
  74. :param node: The node whose vertex operator should be reduced to the identity.
  75. :param avoid: We will try to leave this node alone during the process (if possible).
  76. """
  77. others = set(self.adj[node]) - {avoid}
  78. if self.deterministic:
  79. swap_qubit = min(others) if others else avoid
  80. else:
  81. swap_qubit = others.pop() if others else avoid
  82. for v in reversed(clifford.decompositions[self.node[node]["vop"]]):
  83. if v == "x":
  84. self.local_complementation(node, "U ->")
  85. else:
  86. self.local_complementation(swap_qubit, "V ->")
  87. def local_complementation(self, v, prefix=""):
  88. """ As defined in LISTING 1 of Anders & Briegel """
  89. for i, j in it.combinations(self.adj[v], 2):
  90. self._toggle_edge(i, j)
  91. self.node[v]["vop"] = clifford.times_table[
  92. self.node[v]["vop"], clifford.by_name["msqx_h"]]
  93. for i in self.adj[v]:
  94. self.node[i]["vop"] = clifford.times_table[
  95. self.node[i]["vop"], clifford.by_name["sqz_h"]]
  96. def act_local_rotation(self, node, operation):
  97. """ Act a local rotation on a qubit
  98. :param node: The index of the node to act on
  99. :param operation: The Clifford-group operation to perform. You can use any of the names in the :ref:`Clifford group alias table <clifford>`.
  100. """
  101. rotation = clifford.by_name[str(operation)]
  102. self.node[node]["vop"] = clifford.times_table[
  103. rotation, self.node[node]["vop"]]
  104. def _update_vop(self, v, op):
  105. """ Update a VOP - only used internally"""
  106. rotation = clifford.by_name[str(op)]
  107. self.node[v]["vop"] = clifford.times_table[
  108. self.node[v]["vop"], rotation]
  109. def act_hadamard(self, qubit):
  110. """ Shorthand for ``self.act_local_rotation(qubit, "hadamard")`` """
  111. self.act_local_rotation(qubit, 10)
  112. def _lonely(self, a, b):
  113. """ Is this qubit _lonely ? """
  114. return len(self.adj[a]) > (b in self.adj[a])
  115. def act_cz(self, a, b):
  116. """ Act a controlled-phase gate on two qubits
  117. :param a: The first qubit
  118. :param b: The second qubit
  119. """
  120. if self._lonely(a, b):
  121. self.remove_vop(a, b)
  122. if self._lonely(b, a):
  123. self.remove_vop(b, a)
  124. if self._lonely(a, b) and not clifford.is_diagonal(self.node[a]["vop"]):
  125. self.remove_vop(a, b)
  126. edge = self.has_edge(a, b)
  127. va = self.node[a]["vop"]
  128. vb = self.node[b]["vop"]
  129. new_edge, self.node[a]["vop"], self.node[b]["vop"] = \
  130. clifford.cz_table[int(edge), va, vb]
  131. if new_edge != edge:
  132. self._toggle_edge(a, b)
  133. def measure(self, node, basis, force=None, detail=False):
  134. """ Measure in an arbitrary basis
  135. :param node: The name of the qubit to measure.
  136. :param basis: The basis in which to measure.
  137. :type basis: :math:`\in` ``{"px", "py", "pz"}``
  138. :param force: Measurements in quantum mechanics are probabilistic. If you want to force a particular outcome, use the ``force``.
  139. :type force: boolean
  140. :param detail: Provide detailed information
  141. :type detail: boolean
  142. """
  143. basis = clifford.by_name[basis]
  144. ha = clifford.conjugation_table[self.node[node]["vop"]]
  145. basis, phase = clifford.conjugate(basis, ha)
  146. # Flip a coin
  147. result = force if force != None else random.choice([0, 1])
  148. # Flip the result if we have negative phase
  149. if phase == -1:
  150. result = not result
  151. if basis == clifford.by_name["px"]:
  152. result, determinate = self._measure_graph_x(node, result)
  153. elif basis == clifford.by_name["py"]:
  154. result, determinate = self._measure_graph_y(node, result)
  155. elif basis == clifford.by_name["pz"]:
  156. result, determinate = self._measure_graph_z(node, result)
  157. else:
  158. raise ValueError("You can only measure in {X,Y,Z}")
  159. # Flip the result if we have negative phase
  160. if phase == -1:
  161. result = not result
  162. if detail:
  163. return {"result": int(result),
  164. "determinate": (determinate or force!=None),
  165. "conjugated_basis": basis,
  166. "phase": phase,
  167. "node": node,
  168. "force": force}
  169. else:
  170. return int(result)
  171. def measure_x(self, node, force=None, detail=False):
  172. """ Measure in the X basis
  173. :param node: The name of the qubit to measure.
  174. :param force: Measurements in quantum mechanics are probabilistic. If you want to force a particular outcome, use the ``force``.
  175. :type force: boolean
  176. :param detail: Provide detailed information
  177. :type detail: boolean
  178. """
  179. return self.measure(node, "px", force, detail)
  180. def measure_y(self, node, force=None, detail=False):
  181. """ Measure in the Y basis
  182. :param node: The name of the qubit to measure.
  183. :param force: Measurements in quantum mechanics are probabilistic. If you want to force a particular outcome, use the ``force``.
  184. :type force: boolean
  185. :param detail: Provide detailed information
  186. :type detail: boolean
  187. """
  188. return self.measure(node, "py", force, detail)
  189. def measure_z(self, node, force=None, detail=False):
  190. """ Measure in the Z basis
  191. :param node: The name of the qubit to measure.
  192. :param force: Measurements in quantum mechanics are probabilistic. If you want to force a particular outcome, use the ``force``.
  193. :type force: boolean
  194. :param detail: Provide detailed information
  195. :type detail: boolean
  196. """
  197. return self.measure(node, "pz", force, detail)
  198. def _toggle_edges(self, a, b):
  199. """ Toggle edges between vertex sets a and b """
  200. # TODO: i'm pretty sure this is just a single-line it.combinations or
  201. # equiv
  202. done = set()
  203. for i, j in it.product(a, b):
  204. if i != j and not (i, j) in done:
  205. done.add((i, j))
  206. done.add((j, i))
  207. self._toggle_edge(i, j)
  208. def _measure_graph_x(self, node, result):
  209. """ Measure the bare graph in the X-basis """
  210. if len(self.adj[node]) == 0:
  211. return 0, True
  212. # Pick a vertex
  213. if self.deterministic:
  214. friend = sorted(self.adj[node].keys())[0]
  215. else:
  216. friend = next(self.adj[node].iterkeys())
  217. # Update the VOPs. TODO: pretty ugly
  218. if result:
  219. # Do a z on all ngb(vb) \ ngb(v) \ {v}, and some other stuff
  220. self._update_vop(friend, "msqy")
  221. self._update_vop(node, "pz")
  222. for n in set(self.adj[friend]) - set(self.adj[node]) - {node}:
  223. self._update_vop(n, "pz")
  224. else:
  225. # Do a z on all ngb(v) \ ngb(vb) \ {vb}, and sqy on the friend
  226. self._update_vop(friend, "sqy")
  227. for n in set(self.adj[node]) - set(self.adj[friend]) - {friend}:
  228. self._update_vop(n, "pz")
  229. # Toggle the edges. TODO: Yuk. Just awful!
  230. a = set(self.adj[node].keys())
  231. b = set(self.adj[friend].keys())
  232. self._toggle_edges(a, b)
  233. intersection = a & b
  234. for i, j in it.combinations(intersection, 2):
  235. self._toggle_edge(i, j)
  236. for n in a - {friend}:
  237. self._toggle_edge(friend, n)
  238. return result, False
  239. def _measure_graph_y(self, node, result):
  240. """ Measure the bare graph in the Y-basis """
  241. # Do some rotations
  242. for neighbour in self.adj[node]:
  243. self._update_vop(neighbour, "sqz" if result else "msqz")
  244. # A sort of local complementation
  245. vngbh = set(self.adj[node]) | {node}
  246. for i, j in it.combinations(vngbh, 2):
  247. self._toggle_edge(i, j)
  248. # TODO: naming: # lcoS.herm_adjoint() if result else lcoS
  249. self._update_vop(node, 5 if result else 6)
  250. return result, False
  251. def _measure_graph_z(self, node, result):
  252. """ Measure the bare graph in the Z-basis """
  253. # Disconnect
  254. for neighbour in tuple(self.adj[node]):
  255. self._del_edge(node, neighbour)
  256. if result:
  257. self._update_vop(neighbour, "pz")
  258. # Rotate
  259. if result:
  260. self._update_vop(node, "px")
  261. self._update_vop(node, "hadamard")
  262. else:
  263. self._update_vop(node, "hadamard")
  264. return result, False
  265. def order(self):
  266. """ Get the number of qubits """
  267. return len(self.node)
  268. def __str__(self):
  269. """ Represent as a string for quick debugging """
  270. s = ""
  271. for key in sorted(self.node.keys()):
  272. s += "{}: {}\t".format(
  273. key, clifford.get_name(self.node[key]["vop"]).replace("YC", "-"))
  274. if self.adj[key]:
  275. s += str(tuple(self.adj[key].keys())).replace(" ", "")
  276. else:
  277. s += "-"
  278. s += "\n"
  279. return s
  280. def to_json(self, stringify=False):
  281. """ Convert the graph to JSON-like form.
  282. :param stringify: JSON keys must be strings, But sometimes it is useful to have a JSON-like object whose keys are tuples.
  283. If you want to dump a graph do disk, do something like this::
  284. >>> import json
  285. >>> with open("graph.json") as f:
  286. json.dump(graph.to_json(True), f)
  287. """
  288. if stringify:
  289. node = {str(key): value for key, value in self.node.items()}
  290. adj = {str(key): {str(key): value for key, value in ngbh.items()}
  291. for key, ngbh in self.adj.items()}
  292. return {"node": node, "adj": adj}
  293. else:
  294. return {"node": self.node, "adj": self.adj}
  295. def from_json(self, data):
  296. """ Reconstruct from JSON """
  297. self.__init__([])
  298. # TODO
  299. def to_state_vector(self):
  300. """ Get the full state vector corresponding to this stabilizer state. Useful for debugging, interface with other simulators.
  301. This method becomes very slow for more than about ten qubits!
  302. The output state is represented as a ``abp.qi.CircuitModel``::
  303. >>> print g.to_state_vector()
  304. |00000>: 0.18+0.00j
  305. |00001>: 0.18+0.00j ...
  306. .. todo::
  307. Doesn't work with non-``int`` node labels
  308. """
  309. if len(self.node) > 15:
  310. raise ValueError("Cannot build state vector: too many qubits")
  311. state = qi.CircuitModel(len(self.node))
  312. mapping = {node: i for i, node in enumerate(sorted(self.node))}
  313. for n in self.node:
  314. state.act_hadamard(mapping[n])
  315. for i, j in self.edgelist():
  316. state.act_cz(mapping[i], mapping[j])
  317. for i, n in self.node.items():
  318. state.act_local_rotation(mapping[i], clifford.unitaries[n["vop"]])
  319. return state
  320. def __eq__(self, other):
  321. """ Check equality between GraphStates """
  322. return self.adj == other.adj and self.node == other.node
  323. def copy(self):
  324. """ Make a copy of this graphstate """
  325. g = GraphState()
  326. g.node = self.node.copy()
  327. g.adj = self.adj.copy()
  328. g.deterministic = self.deterministic
  329. return g
  330. if __name__ == '__main__':
  331. g = GraphState()
  332. g.add_nodes(range(10))
  333. g._add_edge(0, 5)
  334. g.act_local_rotation(6, 10)
  335. print g
  336. print g.to_state_vector()