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.

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