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.

481 lines
18KB

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