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.

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