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.

436 lines
16KB

  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: Forces the measurement outcome.
  140. :type force: boolean
  141. :param detail: Get detailed information.
  142. :type detail: boolean
  143. Measurements in quantum mechanics are probabilistic. If you want to force a particular outcome :math:`\in\{0, 1\}`, use ``force``.
  144. You can get more information by setting ``detail=True``, in which case ``measure()`` returns a dictionary with the following keys:
  145. - ``outcome``: the measurement outcome.
  146. - ``determinate``: indicates whether the outcome was determinate or random. For example, measuring :math:`|0\\rangle` in :math:`\sigma_x` always gives a deterministic outcome. ``determinate`` is overridden by ``force`` -- forced outcomes are always determinate.
  147. - ``conjugated_basis``: The index of the measurement operator, rotated by the vertex operator of the measured node, i.e. :math:`U_\\text{vop} \sigma_m U_\\text{vop}^\dagger`.
  148. - ``phase``: The phase of the cojugated basis, :math:`\pm 1`.
  149. - ``node``: The name of the measured node.
  150. - ``force``: The value of ``force``.
  151. """
  152. basis = clifford.by_name[basis]
  153. ha = clifford.conjugation_table[self.node[node]["vop"]]
  154. basis, phase = clifford.conjugate(basis, ha)
  155. # Flip a coin
  156. result = force if force != None else random.choice([0, 1])
  157. # Flip the result if we have negative phase
  158. if phase == -1:
  159. result = not result
  160. if basis == clifford.by_name["px"]:
  161. result, determinate = self._measure_graph_x(node, result)
  162. elif basis == clifford.by_name["py"]:
  163. result, determinate = self._measure_graph_y(node, result)
  164. elif basis == clifford.by_name["pz"]:
  165. result, determinate = self._measure_graph_z(node, result)
  166. else:
  167. raise ValueError("You can only measure in {X,Y,Z}")
  168. # Flip the result if we have negative phase
  169. if phase == -1:
  170. result = not result
  171. if detail:
  172. return {"outcome": int(result),
  173. "determinate": (determinate or force!=None),
  174. "conjugated_basis": basis,
  175. "phase": phase,
  176. "node": node,
  177. "force": force}
  178. else:
  179. return int(result)
  180. def measure_x(self, node, force=None, detail=False):
  181. """ Measure in the X 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, "px", force, detail)
  189. def measure_y(self, node, force=None, detail=False):
  190. """ Measure in the Y 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, "py", force, detail)
  198. def measure_z(self, node, force=None, detail=False):
  199. """ Measure in the Z basis
  200. :param node: The name of the qubit to measure.
  201. :param force: Measurements in quantum mechanics are probabilistic. If you want to force a particular outcome, use the ``force``.
  202. :type force: boolean
  203. :param detail: Provide detailed information
  204. :type detail: boolean
  205. """
  206. return self.measure(node, "pz", force, detail)
  207. def _toggle_edges(self, a, b):
  208. """ Toggle edges between vertex sets a and b """
  209. # TODO: i'm pretty sure this is just a single-line it.combinations or
  210. # equiv
  211. done = set()
  212. for i, j in it.product(a, b):
  213. if i != j and not (i, j) in done:
  214. done.add((i, j))
  215. done.add((j, i))
  216. self._toggle_edge(i, j)
  217. def _measure_graph_x(self, node, result):
  218. """ Measure the bare graph in the X-basis """
  219. if len(self.adj[node]) == 0:
  220. return 0, True
  221. # Pick a vertex
  222. if self.deterministic:
  223. friend = sorted(self.adj[node].keys())[0]
  224. else:
  225. friend = next(self.adj[node].iterkeys())
  226. # Update the VOPs. TODO: pretty ugly
  227. if result:
  228. # Do a z on all ngb(vb) \ ngb(v) \ {v}, and some other stuff
  229. self._update_vop(friend, "msqy")
  230. self._update_vop(node, "pz")
  231. for n in set(self.adj[friend]) - set(self.adj[node]) - {node}:
  232. self._update_vop(n, "pz")
  233. else:
  234. # Do a z on all ngb(v) \ ngb(vb) \ {vb}, and sqy on the friend
  235. self._update_vop(friend, "sqy")
  236. for n in set(self.adj[node]) - set(self.adj[friend]) - {friend}:
  237. self._update_vop(n, "pz")
  238. # Toggle the edges. TODO: Yuk. Just awful!
  239. a = set(self.adj[node].keys())
  240. b = set(self.adj[friend].keys())
  241. self._toggle_edges(a, b)
  242. intersection = a & b
  243. for i, j in it.combinations(intersection, 2):
  244. self._toggle_edge(i, j)
  245. for n in a - {friend}:
  246. self._toggle_edge(friend, n)
  247. return result, False
  248. def _measure_graph_y(self, node, result):
  249. """ Measure the bare graph in the Y-basis """
  250. # Do some rotations
  251. for neighbour in self.adj[node]:
  252. self._update_vop(neighbour, "sqz" if result else "msqz")
  253. # A sort of local complementation
  254. vngbh = set(self.adj[node]) | {node}
  255. for i, j in it.combinations(vngbh, 2):
  256. self._toggle_edge(i, j)
  257. # TODO: naming: # lcoS.herm_adjoint() if result else lcoS
  258. self._update_vop(node, 5 if result else 6)
  259. return result, False
  260. def _measure_graph_z(self, node, result):
  261. """ Measure the bare graph in the Z-basis """
  262. # Disconnect
  263. for neighbour in tuple(self.adj[node]):
  264. self._del_edge(node, neighbour)
  265. if result:
  266. self._update_vop(neighbour, "pz")
  267. # Rotate
  268. if result:
  269. self._update_vop(node, "px")
  270. self._update_vop(node, "hadamard")
  271. else:
  272. self._update_vop(node, "hadamard")
  273. return result, False
  274. def order(self):
  275. """ Get the number of qubits """
  276. return len(self.node)
  277. def __str__(self):
  278. """ Represent as a string for quick debugging """
  279. s = ""
  280. for key in sorted(self.node.keys()):
  281. s += "{}: {}\t".format(
  282. key, clifford.get_name(self.node[key]["vop"]).replace("YC", "-"))
  283. if self.adj[key]:
  284. s += str(tuple(self.adj[key].keys())).replace(" ", "")
  285. else:
  286. s += "-"
  287. s += "\n"
  288. return s
  289. def to_json(self, stringify=False):
  290. """ Convert the graph to JSON-like form.
  291. :param stringify: JSON keys must be strings, But sometimes it is useful to have a JSON-like object whose keys are tuples.
  292. If you want to dump a graph do disk, do something like this::
  293. >>> import json
  294. >>> with open("graph.json") as f:
  295. json.dump(graph.to_json(True), f)
  296. .. todo::
  297. Implement ``from_json()``!
  298. """
  299. if stringify:
  300. node = {str(key): value for key, value in self.node.items()}
  301. adj = {str(key): {str(key): value for key, value in ngbh.items()}
  302. for key, ngbh in self.adj.items()}
  303. return {"node": node, "adj": adj}
  304. else:
  305. return {"node": self.node, "adj": self.adj}
  306. def to_state_vector(self):
  307. """ Get the full state vector corresponding to this stabilizer state. Useful for debugging, interface with other simulators.
  308. This method becomes very slow for more than about ten qubits!
  309. The output state is represented as a ``abp.qi.CircuitModel``::
  310. >>> print g.to_state_vector()
  311. |00000>: 0.18+0.00j
  312. |00001>: 0.18+0.00j ...
  313. """
  314. if len(self.node) > 15:
  315. raise ValueError("Cannot build state vector: too many qubits")
  316. state = qi.CircuitModel(len(self.node))
  317. mapping = {node: i for i, node in enumerate(sorted(self.node))}
  318. for n in self.node:
  319. state.act_hadamard(mapping[n])
  320. for i, j in self.edgelist():
  321. state.act_cz(mapping[i], mapping[j])
  322. for i, n in self.node.items():
  323. state.act_local_rotation(mapping[i], clifford.unitaries[n["vop"]])
  324. return state
  325. def to_stabilizer(self):
  326. """
  327. Get the stabilizer representation of the state::
  328. >>> print g.to_stabilizer()
  329. - X I I I I
  330. I Z I I I
  331. I I Z I I
  332. I I I Z I
  333. I I I I Z
  334. """
  335. return Stabilizer(self)
  336. def __eq__(self, other):
  337. """ Check equality between GraphStates """
  338. return self.adj == other.adj and self.node == other.node
  339. def copy(self):
  340. """ Make a copy of this graphstate """
  341. g = GraphState()
  342. g.node = self.node.copy()
  343. g.adj = self.adj.copy()
  344. g.deterministic = self.deterministic
  345. return g