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.

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