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.

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