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.

515 lines
19KB

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