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.

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