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.

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