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.

456 lines
17KB

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